~ chicken-core (master) /manual/Module (scheme base)


   1[[tags: manual]]
   2[[toc:]]
   3
   4== Module scheme
   5
   6This module provides all of CHICKEN's R7RS procedures and macros.
   7These descriptions are based directly on the ''Revised^7 Report on the
   8Algorithmic Language Scheme''.
   9
  10== Expressions
  11
  12Expression types are categorized as primitive or derived. Primitive
  13expression types include variables and procedure calls. Derived
  14expression types are not semantically primitive, but can instead be
  15defined as macros. The distinction which R7RS makes between primitive
  16and derived is unimportant and does not necessarily reflect how it is
  17implemented in CHICKEN itself.
  18
  19=== Primitive expression types
  20
  21==== Variable references
  22
  23<macro><variable></macro><br>
  24
  25An expression consisting of a variable is a variable reference. The
  26value of the variable reference is the value stored in the location to
  27which the variable is bound. It is an error to reference an unbound
  28variable.
  29
  30 (define x 28)
  31 x           ===>  28
  32
  33==== Literal expressions
  34
  35<macro>(quote <datum>)</macro><br>
  36<macro>'<datum></macro><br>
  37<macro><constant></macro><br>
  38
  39(quote <datum>) evaluates to <datum>. <Datum> may be any external
  40representation of a Scheme object. This notation is used to include
  41literal constants in Scheme code.
  42
  43 (quote a)                    ===>  a
  44 (quote #(a b c))             ===>  #(a b c)
  45 (quote (+ 1 2))              ===>  (+ 1 2)
  46
  47(quote <datum>) may be abbreviated as '<datum>. The two notations are
  48equivalent in all respects.
  49
  50 'a                           ===>  a
  51 '#(a b c)                    ===>  #(a b c)
  52 '()                          ===>  ()
  53 '(+ 1 2)                     ===>  (+ 1 2)
  54 '(quote a)                   ===>  (quote a)
  55 ''a                          ===>  (quote a)
  56
  57Numerical constants, string constants, character constants, and boolean
  58constants evaluate "to themselves"; they need not be quoted.
  59
  60 '"abc"             ===>  "abc"
  61 "abc"              ===>  "abc"
  62 '145932            ===>  145932
  63 145932             ===>  145932
  64 '#t                ===>  #t
  65 #t                 ===>  #t
  66 '#(a 10)           ===>  #(a 10)
  67 #(a 10)            ===>  #(a 10)
  68 '#u8(64 65)        ===>  #u8(64 65)
  69 #u8(64 65)         ===>  #u8(64 65)
  70
  71It is an error to alter a constant (i.e. the value of a literal
  72expression) using a mutation procedure like set-car! or string-set!.
  73In the current implementation of CHICKEN, identical constants don't
  74share memory and it is possible to mutate them, but this may change in
  75the future.
  76
  77==== Procedure calls
  78
  79<macro>(<operator> <operand[1]> ...)</macro><br>
  80
  81A procedure call is written by simply enclosing in parentheses
  82expressions for the procedure to be called and the arguments to be
  83passed to it. The operator and operand expressions are evaluated (in an
  84unspecified order) and the resulting procedure is passed the resulting
  85arguments.
  86
  87 (+ 3 4)                           ===>  7
  88 ((if #f + *) 3 4)                 ===>  12
  89
  90A number of procedures are available as the values of variables in the
  91initial environment; for example, the addition and multiplication
  92procedures in the above examples are the values of the variables + and
  93*.  New procedures are created by evaluating lambda
  94expressions. Procedure calls may return any number of values (see the
  95{{values}} procedure [[#control-features|below]]).
  96
  97Procedure calls are also called combinations.
  98
  99Note:   In contrast to other dialects of Lisp, the order of
 100evaluation is unspecified, and the operator expression and the
 101operand expressions are always evaluated with the same evaluation
 102rules.
 103
 104Note:   Although the order of evaluation is otherwise unspecified,
 105the effect of any concurrent evaluation of the operator and operand
 106expressions is constrained to be consistent with some sequential
 107order of evaluation. The order of evaluation may be chosen
 108differently for each procedure call.
 109
 110Note:   In many dialects of Lisp, the empty combination, (), is a
 111legitimate expression. In Scheme, combinations must have at least
 112one subexpression, so () is not a syntactically valid expression.
 113
 114==== Procedures
 115
 116<macro>(lambda <formals> <body>)</macro><br>
 117
 118Syntax: <Formals> should be a formal arguments list as described below,
 119and <body> should be a sequence of one or more expressions.
 120
 121Semantics: A lambda expression evaluates to a procedure. The
 122environment in effect when the lambda expression was evaluated is
 123remembered as part of the procedure. When the procedure is later called
 124with some actual arguments, the environment in which the lambda
 125expression was evaluated will be extended by binding the variables in
 126the formal argument list to fresh locations, the corresponding actual
 127argument values will be stored in those locations, and the expressions
 128in the body of the lambda expression will be evaluated sequentially in
 129the extended environment. The result(s) of the last expression in the
 130body will be returned as the result(s) of the procedure call.
 131
 132 (lambda (x) (+ x x))              ===>  a procedure
 133 ((lambda (x) (+ x x)) 4)          ===>  8
 134 
 135 (define reverse-subtract
 136   (lambda (x y) (- y x)))
 137 (reverse-subtract 7 10)           ===>  3
 138 
 139 (define add4
 140   (let ((x 4))
 141     (lambda (y) (+ x y))))
 142 (add4 6)                          ===>  10
 143
 144<Formals> should have one of the following forms:
 145
 146*   (<variable[1]> ...): The procedure takes a fixed number of
 147    arguments; when the procedure is called, the arguments will be
 148    stored in the bindings of the corresponding variables.
 149
 150*   <variable>: The procedure takes any number of arguments; when the
 151    procedure is called, the sequence of actual arguments is converted
 152    into a newly allocated list, and the list is stored in the binding
 153    of the <variable>.
 154
 155*   (<variable[1]> ... <variable[n]> . <variable[n+1]>): If a
 156    space-delimited period precedes the last variable, then the
 157    procedure takes n or more arguments, where n is the number of
 158    formal arguments before the period (there must be at least one).
 159    The value stored in the binding of the last variable will be a
 160    newly allocated list of the actual arguments left over after all
 161    the other actual arguments have been matched up against the other
 162    formal arguments.
 163
 164It is an error for a <variable> to appear more than once in <formals>.
 165
 166 ((lambda x x) 3 4 5 6)                  ===>  (3 4 5 6)
 167 ((lambda (x y . z) z)
 168  3 4 5 6)                               ===>  (5 6)
 169
 170Each procedure created as the result of evaluating a lambda expression
 171is (conceptually) tagged with a storage location, in order to make eqv?
 172and eq? work on procedures.
 173
 174As an extension to R7RS, CHICKEN also supports "extended" DSSSL style
 175parameter lists, which allows embedded special keywords.  Such a
 176keyword gives a special meaning to the {{<formal>}} it precedes.
 177DSSSL parameter lists are defined by the following grammar:
 178
 179 <parameter-list> ==> <required-parameter>*
 180                      [#!optional <optional-parameter>*]
 181                      [#!rest <rest-parameter>]
 182                      [#!key <keyword-parameter>*]
 183 <required-parameter> ==> <ident>
 184 <optional-parameter> ==> <ident>
 185                          | (<ident> <initializer>)
 186 <rest-parameter> ==> <ident>
 187 <keyword-parameter> ==> <ident>
 188                         | (<ident> <initializer>)
 189 <initializer> ==> <expr>
 190
 191When a procedure is applied to a list of arguments, the parameters and arguments are processed from left to right as follows:
 192
 193* Required-parameters are bound to successive arguments starting with the first argument. It shall be an error if there are fewer arguments than required-parameters.
 194* Next, the optional-parameters are bound with the remaining arguments. If there are fewer arguments than optional-parameters, then the remaining optional-parameters are bound to the result of the evaluation of their corresponding <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
 195* If there is a rest-parameter, then it is bound to a list containing all the remaining arguments left over after the argument bindings with required-parameters and optional-parameters have been made.
 196* If {{#!key}} was specified in the parameter-list, there should be an even number of remaining arguments. These are interpreted as a series of pairs, where the first member of each pair is a keyword specifying the parameter name, and the second member is the corresponding value. If the same keyword occurs more than once in the list of arguments, then the corresponding value of the first keyword is the binding value. If there is no argument for a particular keyword-parameter, then the variable is bound to the result of evaluating <initializer>, if one was specified, otherwise {{#f}}. The corresponding <initializer> is evaluated in an environment in which all previous parameters have been bound.
 197
 198Needing a special mention is the close relationship between the
 199rest-parameter and possible keyword-parameters.  Declaring a
 200rest-parameter binds up all remaining arguments in a list, as
 201described above. These same remaining arguments are also used for
 202attempted matches with declared keyword-parameters, as described
 203above, in which case a matching keyword-parameter binds to the
 204corresponding value argument at the same time that both the keyword
 205and value arguments are added to the rest parameter list.  Note that
 206for efficiency reasons, the keyword-parameter matching does nothing
 207more than simply attempt to match with pairs that may exist in the
 208remaining arguments.  Extra arguments that don't match are simply
 209unused and forgotten if no rest-parameter has been declared.  Because
 210of this, the caller of a procedure containing one or more
 211keyword-parameters cannot rely on any kind of system error to report
 212wrong keywords being passed in.
 213
 214It shall be an error for an {{<ident>}} to appear more than once in a
 215parameter-list.
 216
 217If there is no rest-parameter and no keyword-parameters in the parameter-list, then it shall be an error for any extra arguments to be passed to the procedure.
 218
 219
 220Example:
 221
 222 ((lambda x x) 3 4 5 6)       => (3 4 5 6)
 223 ((lambda (x y #!rest z) z)
 224  3 4 5 6)                    => (5 6)
 225 ((lambda (x y #!optional z #!rest r #!key i (j 1))
 226     (list x y z i: i j: j))
 227  3 4 5 i: 6 i: 7)            => (3 4 5 i: 6 j: 1)
 228
 229
 230
 231==== Conditionals
 232
 233<macro>(if <test> <consequent> <alternate>)</macro><br>
 234<macro>(if <test> <consequent>)</macro><br>
 235
 236Syntax: <Test>, <consequent>, and <alternate> may be arbitrary
 237expressions.
 238
 239Semantics: An if expression is evaluated as follows: first, <test> is
 240evaluated. If it yields a true value (see [[#Booleans|the section
 241about booleans]] below), then <consequent> is evaluated and its
 242value(s) is(are) returned. Otherwise <alternate> is evaluated and its
 243value(s) is(are) returned. If <test> yields a false value and no
 244<alternate> is specified, then the result of the expression is
 245unspecified.
 246
 247 (if (> 3 2) 'yes 'no)                   ===>  yes
 248 (if (> 2 3) 'yes 'no)                   ===>  no
 249 (if (> 3 2)
 250     (- 3 2)
 251     (+ 3 2))                            ===>  1
 252
 253==== Assignments
 254
 255<macro>(set! <variable> <expression>)</macro><br>
 256
 257<Expression> is evaluated, and the resulting value is stored in the
 258location to which <variable> is bound. <Variable> must be bound either
 259in some region enclosing the set! expression or at top level. The
 260result of the set! expression is unspecified.
 261
 262 (define x 2)
 263 (+ x 1)                         ===>  3
 264 (set! x 4)                      ===>  unspecified
 265 (+ x 1)                         ===>  5
 266
 267As an extension to R7RS, {{set!}} for unbound toplevel variables is
 268allowed.  Also, {{(set! (PROCEDURE ...) ...)}} is supported, as CHICKEN
 269implements [[http://srfi.schemers.org/srfi-17/srfi-17.html|SRFI-17]].
 270
 271==== Inclusion
 272
 273<macro>(include STRING1 STRING2 ...)</macro>
 274<macro>(include-ci STRING1 STRING2 ...)</macro>
 275
 276Semantics: Both {{include}} and {{include-ci}} take one or
 277more filenames expressed as string literals, apply an
 278implementation-specific algorithm to find corresponding
 279files, read the contents of the files in the specified order
 280as if by repeated applications of {{read}}, and effectively replace the {{include}}
 281or {{include-ci}} expression with a {{begin}}
 282expression containing what was read from the files. The
 283difference between the two is that {{include-ci}} reads each
 284file as if it began with the {{#!fold-case}} directive, while
 285{{include}} does not.
 286
 287
 288=== Derived expression types
 289
 290The constructs in this section are hygienic.  For reference purposes,
 291these macro definitions will convert most of the constructs described
 292in this section into the primitive constructs described in the
 293previous section.  This does not necessarily mean that's exactly how
 294it's implemented in CHICKEN.
 295
 296==== Conditionals
 297
 298<macro>(cond <clause[1]> <clause[2]> ...)</macro><br>
 299
 300Syntax: Each <clause> should be of the form
 301
 302 (<test> <expression[1]> ...)
 303
 304where <test> is any expression. Alternatively, a <clause> may be of the
 305form
 306
 307 (<test> => <expression>)
 308
 309The last <clause> may be an "else clause," which has the form
 310
 311 (else <expression[1]> <expression[2]> ...).
 312
 313Semantics: A cond expression is evaluated by evaluating the <test>
 314expressions of successive <clause>s in order until one of them
 315evaluates to a true value (see [[#Booleans|the section about
 316booleans]] below). When a <test> evaluates to a true value, then the
 317remaining <expression>s in its <clause> are evaluated in order, and
 318the result(s) of the last <expression> in the <clause> is(are)
 319returned as the result(s) of the entire cond expression. If the
 320selected <clause> contains only the <test> and no <expression>s, then
 321the value of the <test> is returned as the result.  If the selected
 322<clause> uses the => alternate form, then the <expression> is
 323evaluated. Its value must be a procedure that accepts one argument;
 324this procedure is then called on the value of the <test> and the
 325value(s) returned by this procedure is(are) returned by the cond
 326expression. If all <test>s evaluate to false values, and there is no
 327else clause, then the result of the conditional expression is
 328unspecified; if there is an else clause, then its <expression>s are
 329evaluated, and the value(s) of the last one is(are) returned.
 330
 331 (cond ((> 3 2) 'greater)
 332       ((< 3 2) 'less))           ===>  greater
 333 (cond ((> 3 3) 'greater)
 334       ((< 3 3) 'less)
 335       (else 'equal))             ===>  equal
 336 (cond ((assv 'b '((a 1) (b 2))) => cadr)
 337       (else #f))                 ===>  2
 338
 339
 340As an extension to R7RS, CHICKEN also supports the
 341[[http://srfi.schemers.org/srfi-61|SRFI-61]] syntax:
 342
 343 (<generator> <guard> => <expression>)
 344
 345In this situation, {{generator}} is ''always'' evaluated.  Its
 346resulting value(s) are used as argument(s) for the {{guard}}
 347procedure.  Finally, if {{guard}} returns a non-{{#f}} value, the
 348{{expression}} is evaluated by calling it with the result of
 349{{guard}}.  Otherwise, evaluation procedes to the next clause.
 350
 351<macro>(case <key> <clause[1]> <clause[2]> ...)</macro><br>
 352
 353Syntax: <Key> may be any expression. Each <clause> should have the form
 354
 355 ((<datum[1]> ...) <expression[1]> <expression[2]> ...),
 356
 357where each <datum> is an external representation of some object.
 358Alternatively, as per R7RS, a <clause> may be of the form
 359
 360 ((<datum[1]> ...) => <expression>).
 361
 362All the <datum>s must be distinct. The last <clause> may be an
 363"else clause," which has one of the following two forms:
 364
 365 (else <expression[1]> <expression[2]> ...)
 366 (else => <expression>).
 367
 368Semantics: A case expression is evaluated as follows. <Key> is
 369evaluated and its result is compared against each <datum>. If the
 370result of evaluating <key> is equivalent (in the sense of {{eqv?}};
 371see [[#equivalence-predicates|below]]) to a <datum>, then the
 372expressions in the corresponding <clause> are evaluated from left to
 373right and the result(s) of the last expression in the <clause> is(are)
 374returned as the result(s) of the case expression. If the selected
 375<clause> uses the => alternate form (an R7RS extension), then the
 376<expression> is evaluated. Its value must be a procedure that accepts
 377one argument; this procedure is then called on the value of the <key>
 378and the value(s) returned by this procedure is(are) returned by the
 379case expression.  If the result of evaluating <key> is different from
 380every <datum>, then if there is an else clause its expressions are
 381evaluated and the result(s) of the last is(are) the result(s) of the
 382case expression; otherwise the result of the case expression is
 383unspecified.
 384
 385 (case (* 2 3)
 386   ((2 3 5 7) 'prime)
 387   ((1 4 6 8 9) 'composite))             ===>  composite
 388 (case (car '(c d))
 389   ((a) 'a)
 390   ((b) 'b))                             ===>  unspecified
 391 (case (car '(c d))
 392   ((a e i o u) 'vowel)
 393   ((w y) 'semivowel)
 394   (else 'consonant))                    ===>  consonant
 395
 396<macro>(and <test[1]> ...)</macro><br>
 397
 398The <test> expressions are evaluated from left to right, and the value
 399of the first expression that evaluates to a false value (see
 400[[#Booleans|the section about booleans]]) is returned. Any remaining
 401expressions are not evaluated. If all the expressions evaluate to true
 402values, the value of the last expression is returned. If there are no
 403expressions then #t is returned.
 404
 405 (and (= 2 2) (> 2 1))                   ===>  #t
 406 (and (= 2 2) (< 2 1))                   ===>  #f
 407 (and 1 2 'c '(f g))                     ===>  (f g)
 408 (and)                                   ===>  #t
 409
 410<macro>(or <test[1]> ...)</macro><br>
 411
 412The <test> expressions are evaluated from left to right, and the value
 413of the first expression that evaluates to a true value (see
 414[[#Booleans|the section about booleans]]) is returned. Any remaining
 415expressions are not evaluated. If all expressions evaluate to false
 416values, the value of the last expression is returned. If there are no
 417expressions then #f is returned.
 418
 419 (or (= 2 2) (> 2 1))                    ===>  #t
 420 (or (= 2 2) (< 2 1))                    ===>  #t
 421 (or #f #f #f)         ===>  #f
 422 (or (memq 'b '(a b c))
 423     (/ 3 0))                            ===>  (b c)
 424
 425<macro>(unless TEST EXP1 EXP2 ...)</macro>
 426
 427Equivalent to:
 428
 429<enscript highlight=scheme>
 430(if (not TEST) (begin EXP1 EXP2 ...))
 431</enscript>
 432
 433<macro>(when TEST EXP1 EXP2 ...)</macro>
 434
 435Equivalent to:
 436
 437<enscript highlight=scheme>
 438(if TEST (begin EXP1 EXP2 ...))
 439</enscript>
 440
 441<macro>(cond-expand <ce-clause1> <ce-clause2> ...)</macro>
 442
 443The {{cond-expand}} expression type provides a way
 444to statically expand different expressions depending on the
 445implementation. A <ce-clause> takes the following form:
 446
 447{{
 448(<feature requirement> <expression> ...)
 449}}
 450
 451The last clause can be an "else clause," which has the form
 452
 453{{
 454(else <expression> ...)
 455}}]
 456
 457A feature requirement takes one of the following forms:
 458
 459<feature identifier>
 460
 461{{(library <library name>)}}
 462
 463{{(and <feature requirement> ...)}}
 464
 465{{(or <feature requirement> ...)}}
 466
 467{{(not <feature requirement>)}}
 468
 469Each implementation maintains a list of
 470feature identifiers which are present, as well as a list
 471of libraries which can be imported.
 472The value of a <feature requirement> is determined by replacing each
 473<feature identifier> and {{(library <library name>)}} on the
 474implementation's lists with {{#t}}, and all other feature identifiers and library names with {{#f}}, then evaluating the resulting expression as a Scheme boolean expression under
 475the normal interpretation of {{and}}, {{or}}, and {{not}}.
 476
 477A {{cond-expand}} is then expanded by evaluating the
 478<feature requirement>s of successive <ce-clause>s in order
 479until one of them returns {{#t}}. When a true clause is found,
 480the corresponding <expression>s are expanded to a {{begin}},
 481and the remaining clauses are ignored.
 482
 483If none of the
 484<feature requirement>s evaluate to {{#t}}, then if there is an
 485{{else}} clause, its <expression>s are included. Otherwise, the
 486behavior of the {{cond}}-expand is unspecified. Unlike {{cond}},
 487{{cond-expand}} does not depend on the value of any variables.
 488
 489The following features are built-in and always available by default:
 490{{chicken}}, {{srfi-0}}, {{srfi-2}}, {{srfi-6}}, {{srfi-8}}, {{srfi-9}},
 491{{srfi-11}}, {{srfi-12}}, {{srfi-15}}, {{srfi-16}}, {{srfi-17}}, {{srfi-23}},
 492{{srfi-26}}, {{srfi-28}}, {{srfi-30}}, {{srfi-31}}, {{srfi-39}}, {{srfi-46}},
 493{{srfi-55}}, {{srfi-61}}, {{srfi-62}}, {{srfi-87}}, {{srfi-88}}.
 494
 495There are also situation-specific feature identifiers: {{compiling}} during
 496compilation, {{csi}} when running in the interpreter, and {{compiler-extension}}
 497when running within the compiler.
 498
 499The symbols returned by the following procedures from
 500[[Module (chicken platform)|(chicken platform)]] are also available
 501as feature-identifiers in all situations: {{(machine-byte-order)}},
 502{{(machine-type)}}, {{(software-type)}}, {{(software-version)}}. For
 503example, the {{machine-type}} class of feature-identifiers include
 504{{arm}}, {{alpha}}, {{mips}}, etc.
 505
 506Platform endianness is indicated by the {{little-endian}} and {{big-endian}}
 507features.
 508
 509In addition the following feature-identifiers may exist: {{cross-chicken}},
 510{{dload}}, {{gchooks}}, {{ptables}}, {{case-insensitive}}.
 511
 512
 513==== Binding constructs
 514
 515The three binding constructs let, let*, and letrec give Scheme a block
 516structure, like Algol 60. The syntax of the three constructs is
 517identical, but they differ in the regions they establish for their
 518variable bindings. In a let expression, the initial values are computed
 519before any of the variables become bound; in a let* expression, the
 520bindings and evaluations are performed sequentially; while in a letrec
 521expression, all the bindings are in effect while their initial values
 522are being computed, thus allowing mutually recursive definitions.
 523
 524<macro>(let <bindings> <body>)</macro><br>
 525
 526Syntax: <Bindings> should have the form
 527
 528 ((<variable[1]> <init[1]>) ...),
 529
 530where each <init> is an expression, and <body> should be a sequence of
 531one or more expressions. It is an error for a <variable> to appear more
 532than once in the list of variables being bound.
 533
 534Semantics: The <init>s are evaluated in the current environment (in
 535some unspecified order), the <variable>s are bound to fresh locations
 536holding the results, the <body> is evaluated in the extended
 537environment, and the value(s) of the last expression of <body> is(are)
 538returned. Each binding of a <variable> has <body> as its region.
 539
 540 (let ((x 2) (y 3))
 541   (* x y))                              ===>  6
 542 
 543 (let ((x 2) (y 3))
 544   (let ((x 7)
 545         (z (+ x y)))
 546     (* z x)))                           ===>  35
 547
 548See also "named let", [[#iteration|below]].
 549
 550<macro>(let* <bindings> <body>)</macro><br>
 551
 552Syntax: <Bindings> should have the form
 553
 554 ((<variable[1]> <init[1]>) ...),
 555
 556and <body> should be a sequence of one or more expressions.
 557
 558Semantics: Let* is similar to let, but the bindings are performed
 559sequentially from left to right, and the region of a binding indicated
 560by (<variable> <init>) is that part of the let* expression to the right
 561of the binding. Thus the second binding is done in an environment in
 562which the first binding is visible, and so on.
 563
 564 (let ((x 2) (y 3))
 565   (let* ((x 7)
 566          (z (+ x y)))
 567     (* z x)))                     ===>  70
 568
 569<macro>(letrec <bindings> <body>)</macro><br>
 570
 571Syntax: <Bindings> should have the form
 572
 573 ((<variable[1]> <init[1]>) ...),
 574
 575and <body> should be a sequence of one or more expressions. It is an
 576error for a <variable> to appear more than once in the list of
 577variables being bound.
 578
 579Semantics: The <variable>s are bound to fresh locations holding
 580undefined values, the <init>s are evaluated in the resulting
 581environment (in some unspecified order), each <variable> is assigned to
 582the result of the corresponding <init>, the <body> is evaluated in the
 583resulting environment, and the value(s) of the last expression in
 584<body> is(are) returned. Each binding of a <variable> has the entire
 585letrec expression as its region, making it possible to define mutually
 586recursive procedures.
 587
 588 (letrec ((even?
 589           (lambda (n)
 590             (if (zero? n)
 591                 #t
 592                 (odd? (- n 1)))))
 593          (odd?
 594           (lambda (n)
 595             (if (zero? n)
 596                 #f
 597                 (even? (- n 1))))))
 598   (even? 88))
 599                         ===>  #t
 600
 601One restriction on letrec is very important: it must be possible to
 602evaluate each <init> without assigning or referring to the value of any
 603<variable>. If this restriction is violated, then it is an error. The
 604restriction is necessary because Scheme passes arguments by value
 605rather than by name. In the most common uses of letrec, all the <init>s
 606are lambda expressions and the restriction is satisfied automatically.
 607
 608<macro>(letrec* <bindings> <body>) </macro>
 609
 610Syntax: <Bindings> has the form {{((<variable[1]> <init[1]>) ...)}}, and
 611<body> is a sequence of zero or more
 612definitions followed by one or more expressions as described in section 4.1.4.
 613It is an error for a <variable> to appear more than once in the list of
 614variables being bound.
 615
 616Semantics: The <variable>s are bound to fresh locations, each <variable> is
 617assigned in left-to-right order to the result of evaluating the corresponding
 618<init> (interleaving evaluations and assignments), the <body> is evaluated in
 619the resulting environment, and the values of the last expression in <body> are
 620returned. Despite the left-to-right evaluation and assignment order, each
 621binding of a <variable> has the entire letrec* expression as its region, making
 622it possible to define mutually recursive procedures.
 623
 624If it is not possible to evaluate each <init> without assigning or referring to
 625the value of the corresponding <variable> or the <variable> of any of the
 626bindings that follow it in <bindings>, it is an error. Another restriction is
 627that it is an error to invoke the continuation of an <init> more than once.
 628
 629  ;; Returns the arithmetic, geometric, and
 630  ;; harmonic means of a nested list of numbers
 631  (define (means ton)
 632    (letrec*
 633       ((mean
 634          (lambda (f g)
 635            (f (/ (sum g ton) n))))
 636        (sum
 637          (lambda (g ton)
 638            (if (null? ton)
 639              (+)
 640              (if (number? ton)
 641                  (g ton)
 642                  (+ (sum g (car ton))
 643                     (sum g (cdr ton)))))))
 644        (n (sum (lambda (x) 1) ton)))
 645      (values (mean values values)
 646              (mean exp log)
 647              (mean / /))))
 648
 649Evaluating {{(means '(3 (1 4)))}} returns three values: 8/3, 2.28942848510666
 650(approximately), and 36/19.
 651
 652<macro>(let-values <mv binding spec> <body>)</macro>
 653
 654Syntax: <Mv binding spec> has the form {{((<formals[1]> <init[1]>) ...)}},
 655where each <init> is an expression, and <body> is
 656zero or more definitions followed by a sequence of one or more expressions as
 657described in section 4.1.4. It is an error for a variable to appear more than
 658once in the set of <formals>.
 659
 660Semantics: The <init>s are evaluated in the current environment (in some
 661unspecified order) as if by invoking call-with-values, and the variables
 662occurring in the <formals> are bound to fresh locations holding the values
 663returned by the <init>s, where the <formals> are matched to the return values
 664in the same way that the <formals> in a lambda expression are matched to the
 665arguments in a procedure call. Then, the <body> is evaluated in the extended
 666environment, and the values of the last expression of <body> are returned. Each
 667binding of a <variable> has <body> as its region.
 668
 669It is an error if the <formals> do not match the number of values returned by
 670the corresponding <init>.
 671
 672  (let-values (((root rem) (exact-integer-sqrt 32)))
 673    (* root rem))                 ==>  35
 674
 675<macro>(let*-values <mv binding spec> <body>)</macro>
 676
 677Syntax: <Mv binding spec> has the form {{((<formals> <init>) ...)}},
 678and <body> is a sequence of zero or more definitions
 679followed by one or more expressions as described in section 4.1.4. In each
 680<formals>, it is an error if any variable appears more than once.
 681
 682Semantics: The let*-values construct is similar to let-values, but the <init>s
 683are evaluated and bindings created sequentially from left to right, with the
 684region of the bindings of each <formals> including the <init>s to its right as
 685well as <body>. Thus the second <init> is evaluated in an environment in which
 686the first set of bindings is visible and initialized, and so on.
 687
 688  (let ((a 'a) (b 'b) (x 'x) (y 'y))
 689    (let*-values (((a b) (values x y))
 690                  ((x y) (values a b)))
 691      (list a b x y)))      ===>     (x y x y)
 692
 693==== Sequencing
 694
 695<macro>(begin <expression[1]> <expression[2]> ...)</macro><br>
 696
 697The <expression>s are evaluated sequentially from left to right, and
 698the value(s) of the last <expression> is(are) returned. This expression
 699type is used to sequence side effects such as input and output.
 700
 701 (define x 0)
 702 
 703 (begin (set! x 5)
 704        (+ x 1))                          ===>  6
 705 
 706 (begin (display "4 plus 1 equals ")
 707        (display (+ 4 1)))                ===>  unspecified
 708   and prints  4 plus 1 equals 5
 709
 710As an extension to R7RS, CHICKEN also allows {{(begin)}} without body
 711expressions in any context, not just at toplevel.  This simply
 712evaluates to the unspecified value.
 713
 714
 715==== Iteration
 716
 717<macro>(do ((<variable[1]> <init[1]> <step[1]>) ...) (<test> <expression> ...) <command> ...)</macro><br>
 718
 719Do is an iteration construct. It specifies a set of variables to be
 720bound, how they are to be initialized at the start, and how they are to
 721be updated on each iteration. When a termination condition is met, the
 722loop exits after evaluating the <expression>s.
 723
 724Do expressions are evaluated as follows: The <init> expressions are
 725evaluated (in some unspecified order), the <variable>s are bound to
 726fresh locations, the results of the <init> expressions are stored in
 727the bindings of the <variable>s, and then the iteration phase begins.
 728
 729Each iteration begins by evaluating <test>; if the result is false
 730(see [[#Booleans|the section about booleans]]), then the <command>
 731expressions are evaluated in order for effect, the <step> expressions
 732are evaluated in some unspecified order, the <variable>s are bound to
 733fresh locations, the results of the <step>s are stored in the bindings
 734of the <variable>s, and the next iteration begins.
 735
 736If <test> evaluates to a true value, then the <expression>s are
 737evaluated from left to right and the value(s) of the last <expression>
 738is(are) returned. If no <expression>s are present, then the value of
 739the do expression is unspecified.
 740
 741The region of the binding of a <variable> consists of the entire do
 742expression except for the <init>s. It is an error for a <variable> to
 743appear more than once in the list of do variables.
 744
 745A <step> may be omitted, in which case the effect is the same as if
 746(<variable> <init> <variable>) had been written instead of (<variable>
 747<init>).
 748
 749 (do ((vec (make-vector 5))
 750      (i 0 (+ i 1)))
 751     ((= i 5) vec)
 752   (vector-set! vec i i))                    ===>  #(0 1 2 3 4)
 753 
 754 (let ((x '(1 3 5 7 9)))
 755   (do ((x x (cdr x))
 756        (sum 0 (+ sum (car x))))
 757       ((null? x) sum)))                     ===>  25
 758
 759<macro>(let <variable> <bindings> <body>)</macro><br>
 760
 761"Named let" is a variant on the syntax of let which provides a more
 762general looping construct than do and may also be used to express
 763recursions. It has the same syntax and semantics as ordinary let except
 764that <variable> is bound within <body> to a procedure whose formal
 765arguments are the bound variables and whose body is <body>. Thus the
 766execution of <body> may be repeated by invoking the procedure named by
 767<variable>.
 768
 769 (let loop ((numbers '(3 -2 1 6 -5))
 770            (nonneg '())
 771            (neg '()))
 772   (cond ((null? numbers) (list nonneg neg))
 773         ((>= (car numbers) 0)
 774          (loop (cdr numbers)
 775                (cons (car numbers) nonneg)
 776                neg))
 777         ((< (car numbers) 0)
 778          (loop (cdr numbers)
 779                nonneg
 780                (cons (car numbers) neg)))))
 781                 ===>  ((6 1 3) (-5 -2))
 782
 783====  Dynamic bindings
 784
 785The dynamic extent of a procedure call is the time between when it is initiated
 786and when it returns. In Scheme, {{call-with-current-continuation}}
 787allows reentering a dynamic extent after its procedure call has returned. Thus,
 788the dynamic extent of a call might not be a single, continuous time period.
 789
 790This sections introduces parameter objects, which can be bound to new values
 791for the duration of a dynamic extent. The set of all parameter bindings at a
 792given time is called the dynamic environment.
 793
 794<procedure>(make-parameter init [converter])</procedure>
 795
 796Returns a newly allocated parameter object, which is a procedure that accepts
 797zero arguments and returns the value associated with the parameter object.
 798Initially, this value is the value of {{(converter init)}}, or of {{init}}
 799if the conversion procedure {{converter}} is not specified. The associated value can be temporarily changed
 800using {{parameterize}}, which is described below.
 801
 802The effect of passing arguments to a parameter object is
 803implementation-dependent.
 804
 805<syntax>(parameterize ((<param[1]> <value[1]>) ...) <body>)</syntax>
 806
 807Syntax: Both <param[1]> and <value[1]> are expressions.
 808
 809It is an error if the value of any <param> expression is not a parameter
 810object.
 811
 812Semantics: A parameterize expression is used to change the values returned by
 813specified parameter objects during the evaluation of the body.
 814
 815The <param> and <value> expressions are evaluated in an unspecified order. The
 816<body> is evaluated in a dynamic environment in which calls to the parameters
 817return the results of passing the corresponding values to the conversion
 818procedure specified when the parameters were created. Then the previous values
 819of the parameters are restored without passing them to the conversion
 820procedure. The results of the last expression in the <body> are returned as the
 821results of the entire parameterize expression.
 822
 823Note: If the conversion procedure is not idempotent, the results of
 824(parameterize ((x (x))) ...), which appears to bind the parameter
 825
 826x to its current value, might not be what the user expects.
 827
 828If an implementation supports multiple threads of execution, then parameterize
 829must not change the associated values of any parameters in any thread other
 830than the current thread and threads created inside <body>.
 831
 832Parameter objects can be used to specify configurable settings for a
 833computation without the need to pass the value to every procedure in the call
 834chain explicitly.
 835
 836  (define radix
 837    (make-parameter
 838     10
 839     (lambda (x)
 840       (if (and (exact-integer? x) (<= 2 x 16))
 841           x
 842           (error "invalid radix")))))
 843
 844  (define (f n) (number->string n (radix)))
 845
 846  (f 12)                                        ==> "12"
 847  (parameterize ((radix 2))
 848    (f 12))                                     ==> "1100"
 849  (f 12)                                        ==> "12"
 850
 851  (radix 16)                                    ==> unspecified
 852
 853  (parameterize ((radix 0))
 854    (f 12))                                     ==> error
 855
 856==== Exception handling
 857
 858<macro>(guard (<variable> <cond clause[1]> <cond clause[2]> ...) <body>)</macro>
 859
 860Syntax: Each <cond clause> is as in the specification of cond.
 861
 862Semantics: The <body> is evaluated with an exception handler that binds the
 863raised object (see {{raise}}) to <variable> and, within the scope
 864of that binding, evaluates the clauses as if they were the clauses of a cond
 865expression. That implicit cond expression is evaluated with the continuation
 866and dynamic environment of the guard expression. If every <cond clause>'s
 867<test> evaluates to #f and there is no else clause, then raise-continuable is
 868invoked on the raised object within the dynamic environment of the original
 869call to raise or raise-continuable, except that the current exception handler
 870is that of the guard expression.
 871
 872    (guard (condition
 873             ((assq 'a condition) => cdr)
 874             ((assq 'b condition)))
 875      (raise (list (cons 'a 42))))
 876    ==> 42
 877
 878    (guard (condition
 879             ((assq 'a condition) => cdr)
 880             ((assq 'b condition)))
 881      (raise (list (cons 'b 23))))
 882    ==> (b . 23)
 883
 884==== Quasiquotation
 885
 886<macro>(quasiquote <qq template>)</macro><br>
 887<macro>`<qq template></macro><br>
 888
 889"Backquote" or "quasiquote" expressions are useful for constructing
 890a list or vector structure when most but not all of the desired
 891structure is known in advance. If no commas appear within the <qq
 892template>, the result of evaluating `<qq template> is equivalent to the
 893result of evaluating '<qq template>. If a comma appears within the <qq
 894template>, however, the expression following the comma is evaluated
 895("unquoted") and its result is inserted into the structure instead of
 896the comma and the expression. If a comma appears followed immediately
 897by an at-sign (@), then the following expression must evaluate to a
 898list; the opening and closing parentheses of the list are then
 899"stripped away" and the elements of the list are inserted in place of
 900the comma at-sign expression sequence. A comma at-sign should only
 901appear within a list or vector <qq template>.
 902
 903 `(list ,(+ 1 2) 4)          ===>  (list 3 4)
 904 (let ((name 'a)) `(list ,name ',name))
 905                 ===>  (list a (quote a))
 906 `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b)
 907                 ===>  (a 3 4 5 6 b)
 908 `(( foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))
 909                 ===>  ((foo 7) . cons)
 910 `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8)
 911                 ===>  #(10 5 2 4 3 8)
 912
 913Quasiquote forms may be nested. Substitutions are made only for
 914unquoted components appearing at the same nesting level as the
 915outermost backquote. The nesting level increases by one inside each
 916successive quasiquotation, and decreases by one inside each
 917unquotation.
 918
 919 `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
 920                 ===>  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
 921 (let ((name1 'x)
 922       (name2 'y))
 923   `(a `(b ,,name1 ,',name2 d) e))
 924                 ===>  (a `(b ,x ,'y d) e)
 925
 926The two notations `<qq template> and (quasiquote <qq template>) are
 927identical in all respects. ,<expression> is identical to (unquote
 928<expression>), and ,@<expression> is identical to (unquote-splicing
 929<expression>). The external syntax generated by write for two-element
 930lists whose car is one of these symbols may vary between
 931implementations.
 932
 933 (quasiquote (list (unquote (+ 1 2)) 4))
 934                 ===>  (list 3 4)
 935 '(quasiquote (list (unquote (+ 1 2)) 4))
 936                 ===>  `(list ,(+ 1 2) 4)
 937      i.e., (quasiquote (list (unquote (+ 1 2)) 4))
 938
 939Unpredictable behavior can result if any of the symbols quasiquote,
 940unquote, or unquote-splicing appear in positions within a <qq template>
 941otherwise than as described above.
 942
 943=== Macros
 944
 945Scheme programs can define and use new derived expression types, called
 946macros. Program-defined expression types have the syntax
 947
 948 (<keyword> <datum> ...)
 949
 950where <keyword> is an identifier that uniquely determines the
 951expression type. This identifier is called the syntactic keyword, or
 952simply keyword, of the macro. The number of the <datum>s, and their
 953syntax, depends on the expression type.
 954
 955Each instance of a macro is called a use of the macro. The set of rules
 956that specifies how a use of a macro is transcribed into a more
 957primitive expression is called the transformer of the macro.
 958
 959The macro definition facility consists of two parts:
 960
 961*   A set of expressions used to establish that certain identifiers are
 962    macro keywords, associate them with macro transformers, and control
 963    the scope within which a macro is defined, and
 964
 965*   a pattern language for specifying macro transformers.
 966
 967The syntactic keyword of a macro may shadow variable bindings, and
 968local variable bindings may shadow keyword bindings. All macros defined
 969using the pattern language are "hygienic" and "referentially
 970transparent" and thus preserve Scheme's lexical scoping:
 971
 972*   If a macro transformer inserts a binding for an identifier
 973    (variable or keyword), the identifier will in effect be renamed
 974    throughout its scope to avoid conflicts with other identifiers.
 975    Note that a define at top level may or may not introduce a binding;
 976    this depends on whether the binding already existed before (in which
 977    case its value will be overridden).
 978
 979*   If a macro transformer inserts a free reference to an identifier,
 980    the reference refers to the binding that was visible where the
 981    transformer was specified, regardless of any local bindings that
 982    may surround the use of the macro.
 983
 984==== Binding constructs for syntactic keywords
 985
 986Let-syntax and letrec-syntax are analogous to let and letrec, but they
 987bind syntactic keywords to macro transformers instead of binding
 988variables to locations that contain values. Syntactic keywords may also
 989be bound at top level.
 990
 991<macro>(let-syntax <bindings> <body>)</macro><br>
 992
 993Syntax: <Bindings> should have the form
 994
 995 ((<keyword> <transformer spec>) ...)
 996
 997Each <keyword> is an identifier, each <transformer spec> is an instance
 998of syntax-rules, and <body> should be a sequence of one or more
 999expressions. It is an error for a <keyword> to appear more than once in
 1000the list of keywords being bound.
1001
1002Semantics: The <body> is expanded in the syntactic environment obtained
1003by extending the syntactic environment of the let-syntax expression
1004with macros whose keywords are the <keyword>s, bound to the specified
1005transformers. Each binding of a <keyword> has <body> as its region.
1006
1007 (let-syntax ((when (syntax-rules ()
1008                      ((when test stmt1 stmt2 ...)
1009                       (if test
1010                           (begin stmt1
1011                                  stmt2 ...))))))
1012   (let ((if #t))
1013     (when if (set! if 'now))
1014     if))                                   ===>  now
1015 
1016 (let ((x 'outer))
1017   (let-syntax ((m (syntax-rules () ((m) x))))
1018     (let ((x 'inner))
1019       (m))))                               ===>  outer
1020
1021<macro>(letrec-syntax <bindings> <body>)</macro><br>
1022
1023Syntax: Same as for let-syntax.
1024
1025Semantics: The <body> is expanded in the syntactic environment obtained
1026by extending the syntactic environment of the letrec-syntax expression
1027with macros whose keywords are the <keyword>s, bound to the specified
1028transformers. Each binding of a <keyword> has the <bindings> as well as
1029the <body> within its region, so the transformers can transcribe
1030expressions into uses of the macros introduced by the letrec-syntax
1031expression.
1032
1033 (letrec-syntax
1034   ((my-or (syntax-rules ()
1035             ((my-or) #f)
1036             ((my-or e) e)
1037             ((my-or e1 e2 ...)
1038              (let ((temp e1))
1039                (if temp
1040                    temp
1041                    (my-or e2 ...)))))))
1042   (let ((x #f)
1043         (y 7)
1044         (temp 8)
1045         (let odd?)
1046         (if even?))
1047     (my-or x
1048            (let temp)
1049            (if y)
1050            y)))                ===>  7
1051
1052==== Pattern language
1053
1054A <transformer spec> has the following form:
1055
1056 (syntax-rules <literals> <syntax rule> ...)
1057
1058Syntax: <Literals> is a list of identifiers and each <syntax rule>
1059should be of the form
1060
1061 (<pattern> <template>)
1062
1063The <pattern> in a <syntax rule> is a list <pattern> that begins with
1064the keyword for the macro.
1065
1066A <pattern> is either an identifier, a constant, or one of the
1067following
1068
1069 (<pattern> ...)
1070 (<pattern> <pattern> ... . <pattern>)
1071 (<pattern> ... <pattern> <ellipsis> <pattern> ...)
1072 #(<pattern> ...)
1073 #(<pattern> ... <pattern> <ellipsis>)
1074
1075and a template is either an identifier, a constant, or one of the
1076following
1077
1078 (<element> ...)
1079 (<element> <element> ... . <template>)
1080 (<ellipsis> <template>)
1081 #(<element> ...)
1082
1083where an <element> is a <template> optionally followed by an <ellipsis>
1084and an <ellipsis> is the identifier "...".
1085
1086Semantics: An instance of syntax-rules produces a new macro transformer
1087by specifying a sequence of hygienic rewrite rules. A use of a macro
1088whose keyword is associated with a transformer specified by
1089syntax-rules is matched against the patterns contained in the <syntax
1090rule>s, beginning with the leftmost <syntax rule>. When a match is
1091found, the macro use is transcribed hygienically according to the
1092template.
1093
1094An identifier appearing within a <pattern> can be an underscore ({{_}}), a literal
1095identifier listed in the list of <pattern literal>s, or the <ellipsis>. All
1096other identifiers appearing within a <pattern> are pattern variables.
1097
1098The keyword at the beginning of the pattern in a <syntax rule> is not involved
1099in the matching and is considered neither a pattern variable nor a literal
1100identifier.
1101
1102Pattern variables match arbitrary input elements and are used to refer to
1103elements of the input in the template. It is an error for the same pattern
1104variable to appear more than once in a <pattern>.
1105
1106Underscores also match arbitrary input elements but are not pattern variables
1107and so cannot be used to refer to those elements. If an underscore appears in
1108the <pattern literal>s list, then that takes precedence and underscores in the
1109<pattern> match as literals. Multiple underscores can appear in a <pattern>.
1110
1111Identifiers that appear in (<pattern literal> ...) are interpreted as literal
1112identifiers to be matched against corresponding elements of the input. An
1113element in the input matches a literal identifier if and only if it is an
1114identifier and either both its occurrence in the macro expression and its
1115occurrence in the macro definition have the same lexical binding, or the two
1116identifiers are the same and both have no lexical binding.
1117
1118A subpattern followed by <ellipsis> can match zero or more elements of the
1119input, unless <ellipsis> appears in the <pattern literal>s, in which case it is
1120matched as a literal.
1121
1122More formally, an input form F matches a pattern P if and only if:
1123
1124*   P is an underscore (_).
1125
1126*   P is a non-literal identifier; or
1127
1128*   P is a literal identifier and F is an identifier with the same
1129    binding; or
1130
1131*   P is a list (P[1] ... P[n]) and F is a list of n forms that match P
1132    [1] through P[n], respectively; or
1133
1134*   P is an improper list (P[1] P[2] ... P[n] . P[n+1]) and F is a list
1135    or improper list of n or more forms that match P[1] through P[n],
1136    respectively, and whose nth "cdr" matches P[n+1]; or
1137
1138*   P is of the form (P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n] . P[x]) where E
1139    is a list or improper list of n elements, the first k of which match P[1]
1140    through P[k], whose next m--k elements each match P[e], whose remaining n--m
1141    elements match P[m+1] through P[n], and whose nth and final cdr matches P[x
1142    ]; or
1143
1144*   P is a vector of the form #(P[1] ... P[n]) and F is a vector of n
1145    forms that match P[1] through P[n]; or
1146
1147*   P is of the form #(P[1] ... P[k] P[e] <ellipsis> P[m+1] ... P[n]) where E is a
1148    vector of n elements the first k of which match P[1] through P[k], whose
1149    next m--k elements each match P[e], and whose remaining n--m elements match P
1150    [m+1] through P[n]; or
1151
1152*   P is a datum and F is equal to P in the sense of the equal?
1153    procedure.
1154
1155It is an error to use a macro keyword, within the scope of its binding,
1156in an expression that does not match any of the patterns.
1157
1158When a macro use is transcribed according to the template of the matching
1159<syntax rule>, pattern variables that occur in the template are replaced by the
1160elements they match in the input. Pattern variables that occur in subpatterns
1161followed by one or more instances of the identifier <ellipsis> are allowed only
1162in subtemplates that are followed by as many instances of <ellipsis>. They are
1163replaced in the output by all of the elements they match in the input,
1164distributed as indicated. It is an error if the output cannot be built up as
1165specified.
1166
1167Identifiers that appear in the template but are not pattern variables or the
1168identifier <ellipsis> are inserted into the output as literal identifiers. If a
1169literal identifier is inserted as a free identifier then it refers to the
1170binding of that identifier within whose scope the instance of syntax-rules
1171appears. If a literal identifier is inserted as a bound identifier then it is
1172in effect renamed to prevent inadvertent captures of free identifiers.
1173
1174A template of the form (<ellipsis> <template>) is identical to <template>,
1175except that ellipses within the template have no special meaning. That is, any
1176ellipses contained within <template> are treated as ordinary identifiers. In
1177particular, the template (<ellipsis> <ellipsis>) produces a single <ellipsis>.
1178This allows syntactic abstractions to expand into code containing ellipses.
1179
1180{{
1181(define-syntax be-like-begin
1182  (syntax-rules ()
1183    ((be-like-begin name)
1184     (define-syntax name
1185       (syntax-rules ()
1186         ((name expr (... ...))
1187          (begin expr (... ...))))))))
1188
1189(be-like-begin sequence)
1190
1191(sequence 1 2 3 4)  ==> 4
1192}}
1193
1194As an example, if {{let}} and {{cond}} have their standard meaning
1195then they are hygienic (as required) and the following is not an
1196error.
1197
1198 (let ((=> #f))
1199   (cond (#t => 'ok)))                   ===> ok
1200
1201The macro transformer for cond recognizes => as a local variable, and
1202hence an expression, and not as the top-level identifier =>, which the
1203macro transformer treats as a syntactic keyword. Thus the example
1204expands into
1205
1206 (let ((=> #f))
1207   (if #t (begin => 'ok)))
1208
1209instead of
1210
1211 (let ((=> #f))
1212   (let ((temp #t))
1213     (if temp ('ok temp))))
1214
1215which would result in an invalid procedure call.
1216
1217====  Signaling errors in macro transformers
1218
1219<macro>(syntax-error <message> <args> ...)</macro>
1220
1221{{syntax-error}} behaves similarly to {{error}} except that implementations with
1222an expansion pass separate from evaluation should signal an error as soon as
1223{{syntax-error}} is expanded. This can be used as a syntax-rules <template> for a
1224<pattern> that is an invalid use of the macro, which can provide more
1225descriptive error messages. <message> is a string literal, and <args> arbitrary
1226expressions providing additional information. Applications cannot count on
1227being able to catch syntax errors with exception handlers or guards.
1228
1229 (define-syntax simple-let
1230   (syntax-rules ()
1231     ((_ (head ... ((x . y) val) . tail)
1232         body1 body2 ...)
1233      (syntax-error
1234       "expected an identifier but got"
1235       (x . y)))
1236     ((_ ((name val) ...) body1 body2 ...)
1237      ((lambda (name ...) body1 body2 ...)
1238        val ...))))
1239
1240
1241== Program structure
1242
1243=== Programs
1244
1245A Scheme program consists of a sequence of expressions, definitions,
1246and syntax definitions. Expressions are described in chapter 4;
1247definitions and syntax definitions are the subject of the rest of the
1248present chapter.
1249
1250Programs are typically stored in files or entered interactively to a
1251running Scheme system, although other paradigms are possible;
1252questions of user interface lie outside the scope of this
1253report. (Indeed, Scheme would still be useful as a notation for
1254expressing computational methods even in the absence of a mechanical
1255implementation.)
1256
1257Definitions and syntax definitions occurring at the top level of a
1258program can be interpreted declaratively. They cause bindings to be
1259created in the top level environment or modify the value of existing
1260top-level bindings. Expressions occurring at the top level of a
1261program are interpreted imperatively; they are executed in order when
1262the program is invoked or loaded, and typically perform some kind of
1263initialization.
1264
1265At the top level of a program (begin <form1> ...) is equivalent to the
1266sequence of expressions, definitions, and syntax definitions that form
1267the body of the begin.
1268
1269===  Import declarations
1270
1271<macro>(import IMPORT-SET ...)</macro>
1272
1273An import declaration provides a way to import identifiers exported by a
1274library. Each <import set> names a set of bindings from a library and possibly
1275specifies local names for the imported bindings. It takes one of the following
1276forms:
1277
1278* <library name>
1279
1280* {{(only <import set> <identifier> ...)}}
1281
1282* {{(except <import set> <identifier> ...)}}
1283
1284* {{(prefix <import set> <identifier>)}}
1285
1286* {{(rename <import set> (<identifier[1]> <identifier[2]>) ...)}}
1287
1288In the first form, all of the identifiers in the named library's export clauses
1289are imported with the same names (or the exported names if exported with rename
1290). The additional <import set> forms modify this set as follows:
1291
1292*   only produces a subset of the given <import set> including only the listed
1293    identifiers (after any renaming). It is an error if any of the listed
1294    identifiers are not found in the original set.
1295
1296*   except produces a subset of the given <import set>, excluding the listed
1297    identifiers (after any renaming). It is an error if any of the listed
1298    identifiers are not found in the original set.
1299
1300*   rename modifies the given <import set>, replacing each instance of
1301    <identifier[1]> with <identifier[2]>. It is an error if any of the listed
1302    <identifier[1]>s are not found in the original set.
1303
1304*   prefix automatically renames all identifiers in the given <import set>,
1305    prefixing each with the specified <identifier>.
1306
1307=== Definitions
1308
1309Definitions are valid in some, but not all, contexts where expressions
1310are allowed. They are valid only at the top level of a <program> and
1311at the beginning of a <body>.
1312
1313A definition should have one of the following forms:
1314
1315<macro>(define <variable> <expression>)</macro><br>
1316<macro>(define (<variable> <formals>) <body>)</macro><br>
1317
1318<Formals> should be either a sequence of zero or more variables, or a
1319sequence of one or more variables followed by a space-delimited period
1320and another variable (as in a lambda expression). This form is
1321equivalent to
1322
1323 (define <variable>
1324   (lambda (<formals>) <body>)).
1325
1326<macro>(define <variable>)</macro>
1327
1328This form is a CHICKEN extension to R7RS, and is equivalent to
1329
1330 (define <variable> (void))
1331
1332<macro>(define (<variable> . <formal>) <body>)</macro><br>
1333
1334<Formal> should be a single variable. This form is equivalent to
1335
1336 (define <variable>
1337   (lambda <formal> <body>)).
1338
1339<macro>(define ((<variable> <formal> ...) ...) <body>)</macro><br>
1340
1341As an extension to R7RS, CHICKEN allows ''curried'' definitions, where
1342the variable name may also be a list specifying a name and a nested
1343lambda list. For example,
1344
1345 (define ((make-adder x) y) (+ x y))
1346
1347is equivalent to
1348
1349 (define (make-adder x) (lambda (y) (+ x y))).
1350
1351This type of curried definition can be nested arbitrarily and combined
1352with dotted tail notation or DSSSL keywords.
1353
1354==== Top level definitions
1355
1356At the top level of a program, a definition
1357
1358 (define <variable> <expression>)
1359
1360has essentially the same effect as the assignment expression
1361
1362 (set! <variable> <expression>)
1363
1364if <variable> is bound. If <variable> is not bound, however, then the
1365definition will bind <variable> to a new location before performing
1366the assignment, whereas it would be an error to perform a set! on an
1367unbound variable in standard Scheme.  In CHICKEN, {{set!}} at toplevel
1368has the same effect as a definition, unless inside a module, in which
1369case it is an error.
1370
1371 (define add3
1372   (lambda (x) (+ x 3)))
1373 (add3 3)                         ===>  6
1374 (define first car)
1375 (first '(1 2))                   ===>  1
1376
1377Some implementations of Scheme use an initial environment in which all
1378possible variables are bound to locations, most of which contain
1379undefined values. Top level definitions in such an implementation are
1380truly equivalent to assignments.  In CHICKEN, attempting to evaluate
1381an unbound identifier will result in an error, but you ''can'' use
1382{{set!}} to bind an initial value to it.
1383
1384==== Internal definitions
1385
1386Definitions may occur at the beginning of a <body> (that is, the body
1387of a lambda, let, let*, letrec, let-syntax, or letrec-syntax
1388expression or that of a definition of an appropriate form). Such
1389definitions are known as internal definitions as opposed to the top
1390level definitions described above. The variable defined by an internal
1391definition is local to the <body>. That is, <variable> is bound rather
1392than assigned, and the region of the binding is the entire <body>. For
1393example,
1394
1395 (let ((x 5))
1396   (define foo (lambda (y) (bar x y)))
1397   (define bar (lambda (a b) (+ (* a b) a)))
1398   (foo (+ x 3)))                        ===>  45
1399
1400A <body> containing internal definitions can always be converted into
1401a completely equivalent letrec expression. For example, the let
1402expression in the above example is equivalent to
1403
1404 (let ((x 5))
1405   (letrec ((foo (lambda (y) (bar x y)))
1406            (bar (lambda (a b) (+ (* a b) a))))
1407     (foo (+ x 3))))
1408
1409Just as for the equivalent letrec expression, it must be possible to
1410evaluate each <expression> of every internal definition in a <body>
1411without assigning or referring to the value of any <variable> being
1412defined.
1413
1414Wherever an internal definition may occur (begin <definition1> ...) is
1415equivalent to the sequence of definitions that form the body of the
1416begin.
1417
1418CHICKEN extends the R7RS semantics by allowing internal definitions
1419everywhere, and not only at the beginning of a body. A set of internal
1420definitions is equivalent to a {{letrec}} form enclosing all following
1421expressions in the body:
1422
1423 (let ((foo 123))
1424   (bar)
1425   (define foo 456)
1426   (baz foo) )
1427
1428expands into
1429
1430 (let ((foo 123))
1431   (bar)
1432   (letrec ((foo 456))
1433     (baz foo) ) )
1434
1435Local sequences of {{define-syntax}} forms are translated into
1436equivalent {{letrec-syntax}} forms that enclose the following forms as
1437the body of the expression.
1438
1439===  Multiple-value definitions
1440
1441Another kind of definition is provided by define-values, which creates multiple
1442definitions from a single expression returning multiple values. It is allowed
1443wherever define is allowed.
1444
1445<macro>(define-values <formals> <expression>)</macro>
1446
1447It is an error if a variable appears more than once in the set of <formals>.
1448
1449Semantics: <Expression> is evaluated, and the <formals> are bound to the return
1450values in the same way that the <formals> in a lambda expression are matched to
1451the arguments in a procedure call.
1452
1453    (define-values (x y) (exact-integer-sqrt 17))
1454    (list x y)  ==> (4 1)
1455
1456    (let ()
1457      (define-values (x y) (values 1 2))
1458      (+ x y))      ==> 3
1459
1460=== Syntax definitions
1461
1462Syntax definitions are valid only at the top level of a
1463<program>. They have the following form:
1464
1465<macro>(define-syntax <keyword> <transformer spec>)</macro>
1466
1467{{<Keyword>}} is an identifier, and the {{<transformer spec>}} should
1468be an instance of {{syntax-rules}}.  Note that CHICKEN also supports
1469{{er-macro-transformer}} and {{ir-macro-transformer}} here.  For more
1470information see [[Module (chicken syntax)|the (chicken syntax) module]].
1471
1472The top-level syntactic environment is extended by binding the
1473<keyword> to the specified transformer.
1474
1475In standard Scheme, there is no define-syntax analogue of internal
1476definitions in, but CHICKEN allows these as an extension to the
1477standard.  This means {{define-syntax}} may be used to define local
1478macros that are visible throughout the rest of the body in which the
1479definition occurred, i.e.
1480
1481  (let ()
1482    ...
1483    (define-syntax foo ...)
1484    (define-syntax bar ...)
1485    ...)
1486
1487is expanded into
1488
1489  (let ()
1490    ...
1491    (letrec-syntax ((foo ...) (bar ...))
1492      ...) )
1493
1494{{syntax-rules}} supports [[http://srfi.schemers.org/srfi-46/|SRFI-46]]
1495in allowing the ellipsis identifier to be user-defined by passing it as the first
1496argument to the {{syntax-rules}} form. Also, "tail" patterns of the form
1497
1498  (syntax-rules ()
1499    ((_ (a b ... c)
1500      ...
1501
1502are supported.
1503
1504The effect of destructively modifying the s-expression passed to a
1505transformer procedure is undefined.
1506
1507Although macros may expand into definitions and syntax definitions in
1508any context that permits them, it is an error for a definition or
1509syntax definition to shadow a syntactic keyword whose meaning is
1510needed to determine whether some form in the group of forms that
1511contains the shadowing definition is in fact a definition, or, for
1512internal definitions, is needed to determine the boundary between the
1513group and the expressions that follow the group. For example, the
1514following are errors:
1515
1516 (define define 3)
1517
1518 (begin (define begin list))
1519
1520 (let-syntax
1521   ((foo (syntax-rules ()
1522           ((foo (proc args ...) body ...)
1523            (define proc
1524              (lambda (args ...)
1525                body ...))))))
1526   (let ((x 3))
1527     (foo (plus x y) (+ x y))
1528     (define foo x)
1529     (plus foo x)))
1530
1531=== Record-type definitions
1532
1533Record-type definitions are used to introduce new data types, called record
1534types. Like other definitions, they can appear either at the outermost level or
1535in a body. The values of a record type are called records and are aggregations
1536of zero or more fields, each of which holds a single location. A predicate, a
1537constructor, and field accessors and mutators are defined for each record type.
1538
1539<macro>(define-record-type <name> <constructor> <pred> <field> ...)</macro>
1540
1541Syntax: <name> and <pred> are identifiers. The <constructor> is of the form
1542{{(<constructor name> <field name> ...)}} and each <field> is either of the form
1543{{(<field name> <accessor name>)}} or of the form {{(<field name> <accessor name> <modifier name>)}}. It is an error for the same identifier to occur more than once
1544as a field name. It is also an error for the same identifier to occur more than
1545once as an accessor or mutator name.
1546
1547The define-record-type construct is generative: each use creates a new record
1548type that is distinct from all existing types, including Scheme's predefined
1549types and other record types — even record types of the same name or structure.
1550
1551An instance of define-record-type is equivalent to the following definitions:
1552
1553*   <name> is bound to a representation of the record type itself. This may be
1554    a run-time object or a purely syntactic representation. The representation
1555    is not utilized in this report, but it serves as a means to identify the
1556    record type for use by further language extensions.
1557
1558*   <constructor name> is bound to a procedure that takes as many arguments as
1559    there are <field name>s in the {{(<constructor name> ...)}} subexpression and
1560    returns a new record of type <name>. Fields whose names are listed with
1561    <constructor name> have the corresponding argument as their initial value.
1562    The initial values of all other fields are unspecified. It is an error for
1563    a field name to appear in <constructor> but not as a <field name>.
1564
1565*   <pred> is bound to a predicate that returns #t when given a value returned
1566    by the procedure bound to <constructor name> and #f for everything else.
1567
1568*   Each <accessor name> is bound to a procedure that takes a record of type
1569    <name> and returns the current value of the corresponding field. It is an
1570    error to pass an accessor a value which is not a record of the appropriate
1571    type.
1572
1573*   Each <modifier name> is bound to a procedure that takes a record of type
1574    <name> and a value which becomes the new value of the corresponding field;
1575    an unspecified value is returned. It is an error to pass a modifier a first
1576    argument which is not a record of the appropriate type.
1577
1578For instance, the following record-type definition
1579
1580    (define-record-type <pare>
1581      (kons x y)
1582      pare?
1583      (x kar set-kar!)
1584      (y kdr))
1585
1586defines kons to be a constructor, kar and kdr to be accessors, set-kar! to be a
1587modifier, and pare? to be a predicate for instances of <pare>.
1588
1589    (pare? (kons 1 2))         ===> #t
1590      (pare? (cons 1 2))         ===> #f
1591      (kar (kons 1 2))           ===> 1
1592      (kdr (kons 1 2))           ===> 2
1593      (let ((k (kons 1 2)))
1594        (set-kar! k 3)
1595        (kar k))                 ===> 3
1596
1597As an extension the <modifier name> may have the form
1598{{(setter PROCEDURE)}}, which will define a SRFI-17 setter-procedure
1599for the given {{PROCEDURE}} that sets the field value.
1600Usually {{PROCEDURE}} has the same name is <accessor name> (but it
1601doesn't have to).
1602
1603=== Libraries
1604
1605Libraries provide a way to organize Scheme programs into reusable parts with
1606explicitly defined interfaces to the rest of the program. This section defines
1607the notation and semantics for libraries.
1608
1609====  Library Syntax
1610
1611A library definition takes the following form:
1612
1613<macro>(define-library <library name> <library declaration> ...)</macro>
1614
1615<library name> is a list whose members are identifiers and exact non-negative
1616integers. It is used to identify the library uniquely when importing from other
1617programs or libraries. Libraries whose first identifier is scheme are reserved
1618for use by this report and future versions of this report. Libraries whose
1619first identifier is srfi are reserved for libraries implementing Scheme
1620Requests for Implementation. It is inadvisable, but not an error, for
1621identifiers in library names to contain any of the characters | \ ? * < " : > +
1622[ ] / or control characters after escapes are expanded.
1623
1624A <library declaration> is any of:
1625
1626*   {{(export <export spec> ...)}}
1627
1628*   {{(export-all)}}
1629
1630*   {{(import <import set> ...)}}
1631
1632*   {{(begin <command or definition> ...)}}
1633
1634*   {{(include <filename[1]> <filename[2]> ...)}}
1635
1636*   {{(include-ci <filename[1]> <filename[2]> ...)}}
1637
1638*   {{(include-library-declarations <filename[1]> <filename[2]> ...)}}
1639
1640*   {{(cond-expand <ce-clause[1]> <ce-clause[2]> ...}}
1641
1642An export declaration specifies a list of identifiers which can be made visible
1643to other libraries or programs. An <export spec> takes one of the following
1644forms:
1645
1646* <identifier>
1647
1648* {{(rename <identifier[1]> <identifier[2]>)}}
1649
1650In an <export spec>, an <identifier> names a single binding defined within or
1651imported into the library, where the external name for the export is the same
1652as the name of the binding within the library. A {{rename}} spec exports the
1653binding defined within or imported into the library and named by <identifier
1654[1]> in each {{(<identifier[1]> <identifier[2]>)}} pairing, using <identifier[2]>
1655as the external name.
1656
1657As an extension to R7RS, CHICKEN allows the {{(export-all)}} specifier,
1658which exports all defined entities to be visible when importing the
1659library.
1660
1661An import declaration provides a way to import the identifiers exported by
1662another library.
1663
1664The {{begin}}, {{include}}, and {{include}}-ci declarations are used to specify the body of
1665the library. They have the same syntax and semantics as the corresponding
1666expression types. This form of begin is analogous to, but not the same as, the
1667two types of begin defined in section 4.2.3.
1668
1669The {{include-library-declarations}} declaration is similar to {{include}} except that
1670the contents of the file are spliced directly into the current library
1671definition. This can be used, for example, to share the same export declaration
1672among multiple libraries as a simple form of library interface.
1673
1674The {{cond-expand}} declaration has the same syntax and semantics as the
1675{{cond-expand}} expression type, except that it expands to spliced-in library
1676declarations rather than expressions enclosed in begin.
1677
1678One possible implementation of libraries is as follows: After all {{cond-expand}}
1679library declarations are expanded, a new environment is constructed for the
1680library consisting of all imported bindings. The expressions from all begin,
1681{{include}} and {{include-ci}} library declarations are expanded in that environment in
1682the order in which they occur in the library. Alternatively, {{cond-expand}} and
1683{{import}} declarations may be processed in left to right order interspersed with
1684the processing of other declarations, with the environment growing as imported
1685bindings are added to it by each import declaration.
1686
1687When a library is loaded, its expressions are executed in textual order. If a
1688library's definitions are referenced in the expanded form of a program or
1689library body, then that library must be loaded before the expanded program or
1690library body is evaluated. This rule applies transitively. If a library is
1691imported by more than one program or library, it may possibly be loaded
1692additional times.
1693
1694Similarly, during the expansion of a library (foo), if any syntax keywords
1695imported from another library (bar) are needed to expand the library, then the
1696library (bar) must be expanded and its syntax definitions evaluated before the
1697expansion of (foo).
1698
1699
1700== Standard procedures
1701
1702This chapter describes Scheme's built-in procedures. The initial (or
1703"top level") Scheme environment starts out with a number of variables
1704bound to locations containing useful values, most of which are
1705primitive procedures that manipulate data. For example, the variable
1706abs is bound to (a location initially containing) a procedure of one
1707argument that computes the absolute value of a number, and the variable
1708+ is bound to a procedure that computes sums. Built-in procedures that
1709can easily be written in terms of other built-in procedures are
1710identified as "library procedures".
1711
1712A program may use a top-level definition to bind any variable. It may
1713subsequently alter any such binding by an assignment (see
1714[[#assignments|assignments]], above). These operations do
1715not modify the behavior of Scheme's built-in procedures. Altering any
1716top-level binding that has not been introduced by a definition has an
1717unspecified effect on the behavior of the built-in procedures.
1718
1719=== Equivalence predicates
1720
1721A predicate is a procedure that always returns a boolean value (#t or #f).
1722An equivalence predicate is the computational analogue of a
1723mathematical equivalence relation (it is symmetric, reflexive, and
1724transitive). Of the equivalence predicates described in this section,
1725eq? is the finest or most discriminating, and equal? is the coarsest.
1726eqv? is slightly less discriminating than eq?.
1727
1728<procedure>(eqv? obj[1] obj[2])</procedure><br>
1729
1730The eqv? procedure defines a useful equivalence relation on objects.
1731Briefly, it returns #t if obj[1] and obj[2] should normally be regarded
1732as the same object. This relation is left slightly open to
1733interpretation, but the following partial specification of eqv? holds
1734for all implementations of Scheme.
1735
1736The eqv? procedure returns #t if:
1737
1738*   obj[1] and obj[2] are both #t or both #f.
1739
1740*   obj[1] and obj[2] are both symbols and
1741
1742    (string=? (symbol->string obj1)
1743              (symbol->string obj2))
1744                ===>  #t
1745
1746Note: This assumes that neither obj[1] nor obj[2] is an "uninterned
1747symbol" as alluded to in the section on [[#symbols|symbols]]. This
1748report does not presume to specify the behavior of eqv? on
1749implementation-dependent extensions.
1750
1751*   obj[1] and obj[2] are both numbers, are numerically equal (see =,
1752    under [[#numerical-operations|numerical operations]]), and are
1753    either both exact or both inexact.
1754
1755*   obj[1] and obj[2] are both characters and are the same character
1756    according to the char=? procedure (see "[[#characters|characters]]").
1757
1758*   both obj[1] and obj[2] are the empty list.
1759
1760*   obj[1] and obj[2] are pairs, vectors, or strings that denote the
1761    same locations in the store.
1762
1763*   obj[1] and obj[2] are procedures whose location tags are equal
1764    (see "[[#procedures|procedures]]").
1765
1766The eqv? procedure returns #f if:
1767
1768*   obj[1] and obj[2] are of different types.
1769
1770*   one of obj[1] and obj[2] is #t but the other is #f.
1771
1772*   obj[1] and obj[2] are symbols but
1773
1774    (string=? (symbol->string obj[1])
1775              (symbol->string obj[2]))
1776                ===>  #f
1777
1778*   one of obj[1] and obj[2] is an exact number but the other is an
1779    inexact number.
1780
1781*   obj[1] and obj[2] are numbers for which the = procedure returns #f.
1782
1783*   obj[1] and obj[2] are characters for which the char=? procedure
1784    returns #f.
1785
1786*   one of obj[1] and obj[2] is the empty list but the other is not.
1787
1788*   obj[1] and obj[2] are pairs, vectors, or strings that denote
1789    distinct locations.
1790
1791*   obj[1] and obj[2] are procedures that would behave differently
1792    (return different value(s) or have different side effects) for some
1793    arguments.
1794
1795 (eqv? 'a 'a)                             ===>  #t
1796 (eqv? 'a 'b)                             ===>  #f
1797 (eqv? 2 2)                               ===>  #t
1798 (eqv? '() '())                           ===>  #t
1799 (eqv? 100000000 100000000)               ===>  #t
1800 (eqv? (cons 1 2) (cons 1 2))             ===>  #f
1801 (eqv? (lambda () 1)
1802       (lambda () 2))                     ===>  #f
1803 (eqv? #f 'nil)                           ===>  #f
1804 (let ((p (lambda (x) x)))
1805   (eqv? p p))                            ===>  #t
1806
1807The following examples illustrate cases in which the above rules do not
1808fully specify the behavior of eqv?. All that can be said about such
1809cases is that the value returned by eqv? must be a boolean.
1810
1811 (eqv? "" "")                     ===>  unspecified
1812 (eqv? '#() '#())                 ===>  unspecified
1813 (eqv? (lambda (x) x)
1814       (lambda (x) x))            ===>  unspecified
1815 (eqv? (lambda (x) x)
1816       (lambda (y) y))            ===>  unspecified
1817
1818The next set of examples shows the use of eqv? with procedures that
1819have local state. Gen-counter must return a distinct procedure every
1820time, since each procedure has its own internal counter. Gen-loser,
1821however, returns equivalent procedures each time, since the local state
1822does not affect the value or side effects of the procedures.
1823
1824 (define gen-counter
1825   (lambda ()
1826     (let ((n 0))
1827       (lambda () (set! n (+ n 1)) n))))
1828 (let ((g (gen-counter)))
1829   (eqv? g g))                   ===>  #t
1830 (eqv? (gen-counter) (gen-counter))
1831                                 ===>  #f
1832 (define gen-loser
1833   (lambda ()
1834     (let ((n 0))
1835       (lambda () (set! n (+ n 1)) 27))))
1836 (let ((g (gen-loser)))
1837   (eqv? g g))                   ===>  #t
1838 (eqv? (gen-loser) (gen-loser))
1839                                 ===>  unspecified
1840 
1841 (letrec ((f (lambda () (if (eqv? f g) 'both 'f)))
1842          (g (lambda () (if (eqv? f g) 'both 'g))))
1843   (eqv? f g))
1844                                 ===>  unspecified
1845 
1846 (letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
1847          (g (lambda () (if (eqv? f g) 'g 'both))))
1848   (eqv? f g))
1849                                 ===>  #f
1850
1851Since it is an error to modify constant objects (those returned by
1852literal expressions), implementations are permitted, though not
1853required, to share structure between constants where appropriate. Thus
1854the value of eqv? on constants is sometimes implementation-dependent.
1855
1856 (eqv? '(a) '(a))                         ===>  unspecified
1857 (eqv? "a" "a")                           ===>  unspecified
1858 (eqv? '(b) (cdr '(a b)))                 ===>  unspecified
1859 (let ((x '(a)))
1860   (eqv? x x))                            ===>  #t
1861
1862Rationale:   The above definition of eqv? allows implementations
1863latitude in their treatment of procedures and literals:
1864implementations are free either to detect or to fail to detect that
1865two procedures or two literals are equivalent to each other, and
1866can decide whether or not to merge representations of equivalent
1867objects by using the same pointer or bit pattern to represent both.
1868
1869<procedure>(eq? obj[1] obj[2])</procedure><br>
1870
1871Eq? is similar to eqv? except that in some cases it is capable of
1872discerning distinctions finer than those detectable by eqv?.
1873
1874Eq? and eqv? are guaranteed to have the same behavior on symbols,
1875booleans, the empty list, pairs, procedures, and non-empty strings and
1876vectors. Eq?'s behavior on numbers and characters is
1877implementation-dependent, but it will always return either true or
1878false, and will return true only when eqv? would also return true. Eq?
1879may also behave differently from eqv? on empty vectors and empty
1880strings.
1881
1882 (eq? 'a 'a)                             ===>  #t
1883 (eq? '(a) '(a))                         ===>  unspecified
1884 (eq? (list 'a) (list 'a))               ===>  #f
1885 (eq? "a" "a")                           ===>  unspecified
1886 (eq? "" "")                             ===>  unspecified
1887 (eq? '() '())                           ===>  #t
1888 (eq? 2 2)                               ===>  unspecified
1889 (eq? #\A #\A)                           ===>  unspecified
1890 (eq? car car)                           ===>  #t
1891 (let ((n (+ 2 3)))
1892   (eq? n n))              ===>  unspecified
1893 (let ((x '(a)))
1894   (eq? x x))              ===>  #t
1895 (let ((x '#()))
1896   (eq? x x))              ===>  #t
1897 (let ((p (lambda (x) x)))
1898   (eq? p p))              ===>  #t
1899
1900Rationale:   It will usually be possible to implement eq? much more
1901efficiently than eqv?, for example, as a simple pointer comparison
1902instead of as some more complicated operation. One reason is that
1903it may not be possible to compute eqv? of two numbers in constant
1904time, whereas eq? implemented as pointer comparison will always
1905finish in constant time. Eq? may be used like eqv? in applications
1906using procedures to implement objects with state since it obeys the
1907same constraints as eqv?.
1908
1909<procedure>(equal? obj[1] obj[2])</procedure><br>
1910
1911Equal? recursively compares the contents of pairs, vectors, and
1912strings, applying eqv? on other objects such as numbers and symbols. A
1913rule of thumb is that objects are generally equal? if they print the
1914same. Equal? may fail to terminate if its arguments are circular data
1915structures.
1916
1917 (equal? 'a 'a)                          ===>  #t
1918 (equal? '(a) '(a))                      ===>  #t
1919 (equal? '(a (b) c)
1920         '(a (b) c))                     ===>  #t
1921 (equal? "abc" "abc")                    ===>  #t
1922 (equal? 2 2)                            ===>  #t
1923 (equal? (make-vector 5 'a)
1924         (make-vector 5 'a))             ===>  #t
1925 (equal? (lambda (x) x)
1926         (lambda (y) y))          ===>  unspecified
1927
1928=== Numbers
1929
1930Numerical computation has traditionally been neglected by the Lisp
1931community. Until Common Lisp there was no carefully thought out
1932strategy for organizing numerical computation, and with the exception
1933of the MacLisp system [20] little effort was made to execute numerical
1934code efficiently. This report recognizes the excellent work of the
1935Common Lisp committee and accepts many of their recommendations. In
1936some ways this report simplifies and generalizes their proposals in a
1937manner consistent with the purposes of Scheme.
1938
1939It is important to distinguish between the mathematical numbers, the
1940Scheme numbers that attempt to model them, the machine representations
1941used to implement the Scheme numbers, and notations used to write
1942numbers. This report uses the types number, complex, real, rational,
1943and integer to refer to both mathematical numbers and Scheme numbers.
1944Machine representations such as fixed point and floating point are
1945referred to by names such as fixnum and flonum.
1946
1947==== Numerical types
1948
1949Mathematically, numbers may be arranged into a tower of subtypes in
1950which each level is a subset of the level above it:
1951
1952    number
1953    complex
1954    real
1955    rational
1956    integer
1957
1958For example, 3 is an integer. Therefore 3 is also a rational, a real,
1959and a complex. The same is true of the Scheme numbers that model 3. For
1960Scheme numbers, these types are defined by the predicates number?,
1961complex?, real?, rational?, and integer?.
1962
1963There is no simple relationship between a number's type and its
1964representation inside a computer. Although most implementations of
1965Scheme will offer at least two different representations of 3, these
1966different representations denote the same integer.
1967
1968Scheme's numerical operations treat numbers as abstract data, as
1969independent of their representation as possible. Although an
1970implementation of Scheme may use fixnum, flonum, and perhaps other
1971representations for numbers, this should not be apparent to a casual
1972programmer writing simple programs.
1973
1974It is necessary, however, to distinguish between numbers that are
1975represented exactly and those that may not be. For example, indexes
1976into data structures must be known exactly, as must some polynomial
1977coefficients in a symbolic algebra system. On the other hand, the
1978results of measurements are inherently inexact, and irrational numbers
1979may be approximated by rational and therefore inexact approximations.
1980In order to catch uses of inexact numbers where exact numbers are
1981required, Scheme explicitly distinguishes exact from inexact numbers.
1982This distinction is orthogonal to the dimension of type.
1983
1984==== Exactness
1985
1986Scheme numbers are either exact or inexact. A number is exact if it was
1987written as an exact constant or was derived from exact numbers using
1988only exact operations. A number is inexact if it was written as an
1989inexact constant, if it was derived using inexact ingredients, or if it
1990was derived using inexact operations. Thus inexactness is a contagious
1991property of a number. If two implementations produce exact results for
1992a computation that did not involve inexact intermediate results, the
1993two ultimate results will be mathematically equivalent. This is
1994generally not true of computations involving inexact numbers since
1995approximate methods such as floating point arithmetic may be used, but
1996it is the duty of each implementation to make the result as close as
1997practical to the mathematically ideal result.
1998
1999Rational operations such as + should always produce exact results when
2000given exact arguments. If the operation is unable to produce an exact
2001result, then it may either report the violation of an implementation
2002restriction or it may silently coerce its result to an inexact value.
2003See [[#implementation-restrictions|the next section]].
2004
2005With the exception of inexact->exact, the operations described in this
2006section must generally return inexact results when given any inexact
2007arguments. An operation may, however, return an exact result if it can
2008prove that the value of the result is unaffected by the inexactness of
2009its arguments. For example, multiplication of any number by an exact
2010zero may produce an exact zero result, even if the other argument is
2011inexact.
2012
2013==== Implementation restrictions
2014
2015Implementations of Scheme are not required to implement the whole
2016tower of subtypes given under "[[#Numerical types|Numerical types]]",
2017but they must implement a coherent subset consistent with both the
2018purposes of the implementation and the spirit of the Scheme
2019language. For example, an implementation in which all numbers are real
2020may still be quite useful.
2021
2022Implementations may also support only a limited range of numbers of any
2023type, subject to the requirements of this section. The supported range
2024for exact numbers of any type may be different from the supported range
2025for inexact numbers of that type. For example, an implementation that
2026uses flonums to represent all its inexact real numbers may support a
2027practically unbounded range of exact integers and rationals while
2028limiting the range of inexact reals (and therefore the range of inexact
2029integers and rationals) to the dynamic range of the flonum format.
2030Furthermore the gaps between the representable inexact integers and
2031rationals are likely to be very large in such an implementation as the
2032limits of this range are approached.
2033
2034An implementation of Scheme must support exact integers throughout the
2035range of numbers that may be used for indexes of lists, vectors, and
2036strings or that may result from computing the length of a list, vector,
2037or string. The length, vector-length, and string-length procedures must
2038return an exact integer, and it is an error to use anything but an
2039exact integer as an index. Furthermore any integer constant within the
2040index range, if expressed by an exact integer syntax, will indeed be
2041read as an exact integer, regardless of any implementation restrictions
2042that may apply outside this range. Finally, the procedures listed below
2043will always return an exact integer result provided all their arguments
2044are exact integers and the mathematically expected result is
2045representable as an exact integer within the implementation:
2046
2047 -                     *
2048 +                     abs
2049 ceiling               denominator
2050 exact-integer-sqrt    expt
2051 floor                 floor/
2052 floor-quotient        floor-remainder
2053 gcd                   lcm
2054 max                   min
2055 modulo                numerator
2056 quotient              rationalize
2057 remainder             round
2058 square                truncate
2059 truncate/             truncate-quotient
2060 truncate-remainder
2061
2062CHICKEN follows the IEEE 32-bit and 64-bit floating point
2063standards on all supported platforms.
2064
2065It is the programmer's responsibility to avoid using inexact number objects
2066with magnitude or significand too large to be represented in the
2067implementation.
2068
2069In addition, implementations may distinguish special numbers called positive
2070infinity, negative infinity, NaN, and negative zero.
2071
2072Positive infinity is regarded as an inexact real (but not rational) number that
2073represents an indeterminate value greater than the numbers represented by all
2074rational numbers. Negative infinity is regarded as an inexact real (but not
2075rational) number that represents an indeterminate value less than the numbers
2076represented by all rational numbers.
2077
2078Adding or multiplying an infinite value by any finite real value results in an
2079appropriately signed infinity; however, the sum of positive and negative
2080infinities is a NaN. Positive infinity is the reciprocal of zero, and negative
2081infinity is the reciprocal of negative zero. The behavior of the transcendental
2082functions is sensitive to infinity in accordance with IEEE 754.
2083
2084A NaN is regarded as an inexact real (but not rational) number so indeterminate
2085that it might represent any real value, including positive or negative
2086infinity, and might even be greater than positive infinity or less than
2087negative infinity. An implementation that does not support non-real numbers may
2088use NaN to represent non-real values like (sqrt -1.0) and (asin 2.0).
2089
2090A NaN always compares false to any number, including a NaN. An arithmetic
2091operation where one operand is NaN returns NaN, unless the implementation can
2092prove that the result would be the same if the NaN were replaced by any
2093rational number. Dividing zero by zero results in NaN unless both zeros are
2094exact.
2095
2096Negative zero is an inexact real value written -0.0 and is distinct (in the
2097sense of eqv?) from 0.0. A Scheme implementation is not required to distinguish
2098negative zero. If it does, however, the behavior of the transcendental
2099functions is sensitive to the distinction in accordance with IEEE 754.
2100Specifically, in a Scheme implementing both complex numbers and negative zero,
2101the branch cut of the complex logarithm function is such that (imag-part (log
2102-1.0-0.0i)) is --π rather than π.
2103
2104Furthermore, the negation of negative zero is ordinary zero and vice versa.
2105This implies that the sum of two or more negative zeros is negative, and the
2106result of subtracting (positive) zero from a negative zero is likewise
2107negative. However, numerical comparisons treat negative zero as equal to zero.
2108
2109Note that both the real and the imaginary parts of a complex number can be
2110infinities, NaNs, or negative zero.
2111
2112
2113==== Syntax of numerical constants
2114
2115For a complete formal description of the syntax of the written
2116representations for numbers, see the R7RS report. Note that case is
2117not significant in numerical constants.
2118
2119A number may be written in binary, octal, decimal, or hexadecimal by
2120the use of a radix prefix. The radix prefixes are #b (binary), #o
2121(octal), #d (decimal), and #x (hexadecimal). With no radix prefix, a
2122number is assumed to be expressed in decimal.
2123
2124A numerical constant may be specified to be either exact or inexact by
2125a prefix. The prefixes are #e for exact, and #i for inexact. An
2126exactness prefix may appear before or after any radix prefix that is
2127used. If the written representation of a number has no exactness
2128prefix, the constant may be either inexact or exact. It is inexact if
2129it contains a decimal point, an exponent, or a "#" character in the
2130place of a digit, otherwise it is exact. In systems with inexact
2131numbers of varying precisions it may be useful to specify the precision
2132of a constant. For this purpose, numerical constants may be written
2133with an exponent marker that indicates the desired precision of the
2134inexact representation. The letters s, f, d, and l specify the use of
2135short, single, double, and long precision, respectively. (When fewer
2136than four internal inexact representations exist, the four size
2137specifications are mapped onto those available. For example, an
2138implementation with two internal representations may map short and
2139single together and long and double together.) In addition, the
2140exponent marker e specifies the default precision for the
2141implementation. The default precision has at least as much precision as
2142double, but implementations may wish to allow this default to be set by
2143the user.
2144
2145 3.14159265358979F0
2146         Round to single --- 3.141593
2147 0.6L0
2148         Extend to long --- .600000000000000
2149
2150==== Numerical operations
2151
2152The numerical routines described below have argument restrictions,
2153which are encoded in the naming conventions of the arguments as
2154given in the procedure's signature.  The conventions are as follows:
2155
2156; {{obj}} : any object
2157; {{list, list1, ... listj, ...	list}} : (see "[[#pairs-and-lists|Pairs and lists]]" below)
2158; {{z, z1, ... zj, ...}} : complex number
2159; {{x, x1, ... xj, ...}} : real number
2160; {{y, y1, ... yj, ...}} : real number
2161; {{q, q1, ... qj, ...}} : rational number
2162; {{n, n1, ... nj, ...}} : integer
2163; {{k, k1, ... kj, ...}} : exact non-negative integer
2164
2165The examples used in this section assume that any
2166numerical constant written using an exact notation is indeed
2167represented as an exact number. Some examples also assume that certain
2168numerical constants written using an inexact notation can be
2169represented without loss of accuracy; the inexact constants were chosen
2170so that this is likely to be true in implementations that use flonums
2171to represent inexact numbers.
2172
2173<procedure>(number? obj)</procedure><br>
2174<procedure>(complex? obj)</procedure><br>
2175<procedure>(real? obj)</procedure><br>
2176<procedure>(rational? obj)</procedure><br>
2177<procedure>(integer? obj)</procedure><br>
2178
2179These numerical type predicates can be applied to any kind of argument,
2180including non-numbers. They return #t if the object is of the named
2181type, and otherwise they return #f. In general, if a type predicate is
2182true of a number then all higher type predicates are also true of that
2183number. Consequently, if a type predicate is false of a number, then
2184all lower type predicates are also false of that number. If z is an
2185inexact complex number, then (real? z) is true if and only if (zero?
2186(imag-part z)) is true. If x is an inexact real number, then (integer?
2187x) is true if and only if (= x (round x)).
2188
2189 (complex? 3+4i)                 ===>  #t
2190 (complex? 3)                    ===>  #t
2191 (real? 3)                       ===>  #t
2192 (real? -2.5+0.0i)               ===>  #t
2193 (real? #e1e10)                  ===>  #t
2194 (rational? 6/10)                ===>  #t
2195 (rational? 6/3)                 ===>  #t
2196 (integer? 3+0i)                 ===>  #t
2197 (integer? 3.0)                  ===>  #t
2198 (integer? 8/4)                  ===>  #t
2199
2200Note:   The behavior of these type predicates on inexact numbers is
2201unreliable, since any inaccuracy may affect the result.
2202
2203Note:   In many implementations the rational? procedure will be the
2204same as real?, and the complex? procedure will be the same as
2205number?, but unusual implementations may be able to represent some
2206irrational numbers exactly or may extend the number system to
2207support some kind of non-complex numbers.
2208
2209<procedure>(exact? z)</procedure><br>
2210<procedure>(inexact? z)</procedure><br>
2211
2212These numerical predicates provide tests for the exactness of a
2213quantity. For any Scheme number, precisely one of these predicates is
2214true.
2215
2216<procedure>(exact-integer? z)</procedure>
2217
2218Returns #t if z is both exact and an integer; otherwise returns #f.
2219
2220 (exact-integer? 32)  ===> #t
2221 (exact-integer? 32.0)  ===> #f
2222 (exact-integer? 32/5)  ===> #f
2223
2224<procedure>(= z[1] z[2] z[3] ...)</procedure><br>
2225<procedure>(< x[1] x[2] x[3] ...)</procedure><br>
2226<procedure>(> x[1] x[2] x[3] ...)</procedure><br>
2227<procedure>(<= x[1] x[2] x[3] ...)</procedure><br>
2228<procedure>(>= x[1] x[2] x[3] ...)</procedure><br>
2229
2230These procedures return #t if their arguments are (respectively):
2231equal, monotonically increasing, monotonically decreasing,
2232monotonically nondecreasing, or monotonically nonincreasing.
2233
2234These predicates are required to be transitive.
2235
2236Note:   The traditional implementations of these predicates in
2237Lisp-like languages are not transitive.
2238
2239Note:   While it is not an error to compare inexact numbers using
2240these predicates, the results may be unreliable because a small
2241inaccuracy may affect the result; this is especially true of = and
2242zero?. When in doubt, consult a numerical analyst.
2243
2244<procedure>(zero? z)</procedure><br>
2245<procedure>(positive? x)</procedure><br>
2246<procedure>(negative? x)</procedure><br>
2247<procedure>(odd? n)</procedure><br>
2248<procedure>(even? n)</procedure><br>
2249
2250These numerical predicates test a number for a particular property,
2251returning #t or #f. See note above.
2252
2253<procedure>(max x[1] x[2] ...)</procedure><br>
2254<procedure>(min x[1] x[2] ...)</procedure><br>
2255
2256These procedures return the maximum or minimum of their arguments.
2257
2258 (max 3 4)                      ===>  4    ; exact
2259 (max 3.9 4)                    ===>  4.0  ; inexact
2260
2261Note:   If any argument is inexact, then the result will also be
2262inexact (unless the procedure can prove that the inaccuracy is not
2263large enough to affect the result, which is possible only in
2264unusual implementations). If min or max is used to compare numbers
2265of mixed exactness, and the numerical value of the result cannot be
2266represented as an inexact number without loss of accuracy, then the
2267procedure may report a violation of an implementation restriction.
2268
2269<procedure>(+ z[1] ...)</procedure><br>
2270<procedure>(* z[1] ...)</procedure><br>
2271
2272These procedures return the sum or product of their arguments.
2273
2274 (+ 3 4)                         ===>  7
2275 (+ 3)                           ===>  3
2276 (+)                             ===>  0
2277 (* 4)                           ===>  4
2278 (*)                             ===>  1
2279
2280<procedure>(- z[1] z[2])</procedure><br>
2281<procedure>(- z)</procedure><br>
2282<procedure>(- z[1] z[2] ...)</procedure><br>
2283<procedure>(/ z[1] z[2])</procedure><br>
2284<procedure>(/ z)</procedure><br>
2285<procedure>(/ z[1] z[2] ...)</procedure><br>
2286
2287With two or more arguments, these procedures return the difference or
2288quotient of their arguments, associating to the left. With one
2289argument, however, they return the additive or multiplicative inverse
2290of their argument.
2291
2292 (- 3 4)                         ===>  -1
2293 (- 3 4 5)                       ===>  -6
2294 (- 3)                           ===>  -3
2295 (/ 3 4 5)                       ===>  3/20
2296 (/ 3)                           ===>  1/3
2297
2298<procedure>(abs x)</procedure><br>
2299
2300Abs returns the absolute value of its argument.
2301
2302 (abs -7)                        ===>  7
2303
2304<procedure>(floor/ n[1] n[2])</procedure><br>
2305<procedure>(floor-quotient n[1] n[2])</procedure><br>
2306<procedure>(floor-remainder n[1] n[2])</procedure><br>
2307<procedure>(truncate/ n[1] n[2])</procedure><br>
2308<procedure>(truncate-quotient n[1] n[2])</procedure><br>
2309<procedure>(truncate-remainder n[1] n[2])</procedure><br>
2310
2311These procedures implement number-theoretic (integer) division. It is an error
2312if n[2] is zero. The procedures ending in / return two integers; the other
2313procedures return an integer. All the procedures compute a quotient n[q] and remainder
2314n[r] such that n[1] = n[2] * n[q] + n[r]. For each of the division operators, there are three procedures defined as
2315follows:
2316
2317 (<operator>/ n[1] n[2]) ==> n[q] n[r]
2318 (<operator>-quotient n[1] n[2]) ==> n[q]
2319 (<operator>-remainder n[1] n[2]) ==> n[r]
2320
2321The remainder n[r] is determined by the choice of integer n[q]: n[r] = n[1] -- n[2] * n[q]. Each set of operators uses a different choice of n[q]:
2322
2323 floor    n[q] = ⌊n[1] / n[2]⌋
2324 truncate n[q] = runcate(n[1] / n[2])
2325
2326For any of the operators, and for integers n[1] and n[2] with n[2] not equal to 0,
2327
2328 (= n[1] (+ (* n[2] (<operator>-quotient n[1] n[2]))
2329         (<operator>-remainder n[1] n[2])))
2330         ==> #t
2331
2332provided all numbers involved in that computation are exact.
2333
2334Examples:
2335
2336 (floor/ 5 2)          ==> 2 1
2337 (floor/ -5 2)         ==> -3 1
2338 (floor/ 5 -2)         ==> -3 -1
2339 (floor/ -5 -2)        ==> 2 -1
2340 (truncate/ 5 2)       ==> 2 1
2341 (truncate/ -5 2)      ==> -2 -1
2342 (truncate/ 5 -2)      ==> -2 1
2343 (truncate/ -5 -2)     ==> 2 -1
2344 (truncate/ -5.0 -2)   ==> 2.0 -1.0
2345
2346<procedure>(quotient n[1] n[2])</procedure><br>
2347<procedure>(remainder n[1] n[2])</procedure><br>
2348<procedure>(modulo n[1] n[2])</procedure><br>
2349
2350These procedures implement number-theoretic (integer) division. n[2]
2351should be non-zero. All three procedures return integers. If n[1]/n[2]
2352is an integer:
2353
2354    (quotient n[1] n[2])           ===> n[1]/n[2]
2355    (remainder n[1] n[2])          ===> 0
2356    (modulo n[1] n[2])             ===> 0
2357
2358If n[1]/n[2] is not an integer:
2359
2360    (quotient n[1] n[2])           ===> n[q]
2361    (remainder n[1] n[2])          ===> n[r]
2362    (modulo n[1] n[2])             ===> n[m]
2363
2364where n[q] is n[1]/n[2] rounded towards zero, 0 < |n[r]| < |n[2]|, 0 <
2365|n[m]| < |n[2]|, n[r] and n[m] differ from n[1] by a multiple of n[2],
2366n[r] has the same sign as n[1], and n[m] has the same sign as n[2].
2367
2368From this we can conclude that for integers n[1] and n[2] with n[2] not
2369equal to 0,
2370
2371     (= n[1] (+ (* n[2] (quotient n[1] n[2]))
2372           (remainder n[1] n[2])))
2373                                         ===>  #t
2374
2375provided all numbers involved in that computation are exact.
2376
2377 (modulo 13 4)                   ===>  1
2378 (remainder 13 4)                ===>  1
2379 
2380 (modulo -13 4)                  ===>  3
2381 (remainder -13 4)               ===>  -1
2382 
2383 (modulo 13 -4)                  ===>  -3
2384 (remainder 13 -4)               ===>  1
2385 
2386 (modulo -13 -4)                 ===>  -1
2387 (remainder -13 -4)              ===>  -1
2388 
2389 (remainder -13 -4.0)            ===>  -1.0  ; inexact
2390
2391<procedure>(gcd n[1] ...)</procedure><br>
2392<procedure>(lcm n[1] ...)</procedure><br>
2393
2394These procedures return the greatest common divisor or least common
2395multiple of their arguments. The result is always non-negative.
2396
2397 (gcd 32 -36)                    ===>  4
2398 (gcd)                           ===>  0
2399 (lcm 32 -36)                    ===>  288
2400 (lcm 32.0 -36)                  ===>  288.0  ; inexact
2401 (lcm)                           ===>  1
2402
2403<procedure>(numerator q)</procedure><br>
2404<procedure>(denominator q)</procedure><br>
2405
2406These procedures return the numerator or denominator of their argument;
2407the result is computed as if the argument was represented as a fraction
2408in lowest terms. The denominator is always positive. The denominator of
24090 is defined to be 1.
2410
2411 (numerator (/ 6 4))            ===>  3
2412 (denominator (/ 6 4))          ===>  2
2413 (denominator
2414   (exact->inexact (/ 6 4)))    ===> 2.0
2415
2416<procedure>(floor x)</procedure><br>
2417<procedure>(ceiling x)</procedure><br>
2418<procedure>(truncate x)</procedure><br>
2419<procedure>(round x)</procedure><br>
2420
2421These procedures return integers. Floor returns the largest integer not
2422larger than x. Ceiling returns the smallest integer not smaller than x.
2423Truncate returns the integer closest to x whose absolute value is not
2424larger than the absolute value of x. Round returns the closest integer
2425to x, rounding to even when x is halfway between two integers.
2426
2427Rationale:   Round rounds to even for consistency with the default
2428rounding mode specified by the IEEE floating point standard.
2429
2430Note:   If the argument to one of these procedures is inexact, then
2431the result will also be inexact. If an exact value is needed, the
2432result should be passed to the inexact->exact procedure.
2433
2434 (floor -4.3)                  ===>  -5.0
2435 (ceiling -4.3)                ===>  -4.0
2436 (truncate -4.3)               ===>  -4.0
2437 (round -4.3)                  ===>  -4.0
2438 
2439 (floor 3.5)                   ===>  3.0
2440 (ceiling 3.5)                 ===>  4.0
2441 (truncate 3.5)                ===>  3.0
2442 (round 3.5)                   ===>  4.0  ; inexact
2443 
2444 (round 7/2)                   ===>  4    ; exact
2445 (round 7)                     ===>  7
2446
2447<procedure>(rationalize x y)</procedure><br>
2448
2449Rationalize returns the simplest rational number differing from x by no
2450more than y. A rational number r[1] is simpler than another rational
2451number r[2] if r[1] = p[1]/q[1] and r[2] = p[2]/q[2] (in lowest terms)
2452and |p[1]| < |p[2]| and |q[1]| < |q[2]|. Thus 3/5 is simpler than 4/7.
2453Although not all rationals are comparable in this ordering (consider 2/
24547 and 3/5) any interval contains a rational number that is simpler than
2455every other rational number in that interval (the simpler 2/5 lies
2456between 2/7 and 3/5). Note that 0 = 0/1 is the simplest rational of
2457all.
2458
2459 (rationalize
2460   (inexact->exact .3) 1/10)          ===> 1/3    ; exact
2461 (rationalize .3 1/10)                ===> #i1/3  ; inexact
2462
2463<procedure>(square z)</procedure>
2464
2465Returns the square of z. This is equivalent to {{(* z z)}}-
2466
2467 (square 42)        ==> 1764
2468 (square 2.0)      ==> 4.0
2469
2470<procedure>(exact-integer-sqrt k)</procedure>
2471
2472Returns two non-negative exact integers s and r where k = s^2 + r and k < (s + 1)^2.
2473
2474 (exact-integer-sqrt 4)  ==> 2 0
2475 (exact-integer-sqrt 5)  ==> 2 1
2476
2477<procedure>(expt z[1] z[2])</procedure><br>
2478
2479Returns z[1] raised to the power z[2]. For z[1] != 0
2480
2481 z[1]^z[2] = e^z[2] log z[1]
2482
24830^z is 1 if z = 0 and 0 otherwise.
2484
2485<procedure>(exact z)</procedure><br>
2486<procedure>(inexact z)</procedure><br>
2487
2488The procedure {{inexact}}  returns an inexact representation of z. The value returned is the inexact number that is numerically closest to the
2489argument. For inexact arguments, the result is the same as the argument. For
2490exact complex numbers, the result is a complex number whose real and imaginary
2491parts are the result of applying inexact to the real and imaginary parts of the
2492argument, respectively. If an exact argument has no reasonably close inexact
2493equivalent (in the sense of =), then a violation of an implementation
2494restriction may be reported.
2495
2496The procedure {{exact}} returns an exact representation of z. The value returned is the exact number that is numerically closest to the
2497argument. For exact arguments, the result is the same as the argument. For
2498inexact non-integral real arguments, the implementation may return a rational
2499approximation, or may report an implementation violation. For inexact complex
2500arguments, the result is a complex number whose real and imaginary parts are
2501the result of applying exact to the real and imaginary parts of the argument,
2502respectively. If an inexact argument has no reasonably close exact equivalent,
2503(in the sense of =), then a violation of an implementation restriction may be
2504reported.
2505
2506==== Numerical input and output
2507
2508<procedure>(number->string z [radix])</procedure>
2509
2510Radix must be an exact integer.  The R7RS standard only requires
2511implementations to support 2, 8, 10, or 16, but CHICKEN allows any
2512radix between 2 and 36, inclusive (note: due to a bug, flonums with
2513fractional components always use radix 10, irrespective of the argument).
2514If omitted, radix defaults to 10. The procedure number->string takes
2515a number and a radix and returns as a string an external
2516representation of the given number in the given radix such that
2517
2518 (let ((number number)
2519       (radix radix))
2520   (eqv? number
2521         (string->number (number->string number
2522                                         radix)
2523                         radix)))
2524
2525is true. It is an error if no possible result makes this expression
2526true.
2527
2528If z is inexact, the radix is 10, and the above expression can be
2529satisfied by a result that contains a decimal point, then the result
2530contains a decimal point and is expressed using the minimum number of
2531digits (exclusive of exponent and trailing zeroes) needed to make the
2532above expression true [3, 5]; otherwise the format of the result is
2533unspecified.
2534
2535The result returned by number->string never contains an explicit radix
2536prefix.
2537
2538Note:   The error case can occur only when z is not a complex
2539number or is a complex number with a non-rational real or imaginary
2540part.
2541
2542Rationale:   If z is an inexact number represented using flonums,
2543and the radix is 10, then the above expression is normally
2544satisfied by a result containing a decimal point. The unspecified
2545case allows for infinities, NaNs, and non-flonum representations.
2546
2547As an extension to R7RS, CHICKEN supports reading and writing the
2548special IEEE floating-point numbers ''+nan'', ''+inf'' and ''-inf'',
2549as well as negative zero.
2550
2551<procedure>(string->number string)</procedure><br>
2552<procedure>(string->number string radix)</procedure><br>
2553
2554Returns a number of the maximally precise representation expressed by
2555the given string.  Radix must be an exact integer.  The R7RS standard
2556only requires implementations to support 2, 8, 10, or 16, but CHICKEN
2557allows any radix between 2 and 36, inclusive.  If supplied, radix is a
2558default radix that may be overridden by an explicit radix prefix in
2559string (e.g. "#o177"). If radix is not supplied, then the default
2560radix is 10. If string is not a syntactically valid notation for a
2561number, then string->number returns #f.
2562
2563If the radix is higher than 18, the parser treats ambiguous syntax
2564that might be a complex number, like {{{"+i"}}} and {{{"-i"}}} (and
2565any prefixes like {{{"+1234i"}}}), as an integer.  If you want this to
2566be parsed as a complex number, explicitly write down {{{"0+i"}}} to
2567disambiguate.  Note that {{{number->string}}} will always emit complex
2568numbers using the full notation, so it can always be read back by
2569{{{string->number}}}.
2570
2571 (string->number "100")                ===>  100
2572 (string->number "100" 16)             ===>  256
2573 (string->number "1e2")                ===>  100.0
2574 (string->number "15##")               ===>  1500.0
2575
2576Note:   The domain of string->number may be restricted by
2577implementations in the following ways. String->number is permitted
2578to return #f whenever string contains an explicit radix prefix. If
2579all numbers supported by an implementation are real, then string->
2580number is permitted to return #f whenever string uses the polar or
2581rectangular notations for complex numbers. If all numbers are
2582integers, then string->number may return #f whenever the fractional
2583notation is used. If all numbers are exact, then string->number may
2584return #f whenever an exponent marker or explicit exactness prefix
2585is used, or if a # appears in place of a digit. If all inexact
2586numbers are integers, then string->number may return #f whenever a
2587decimal point is used.
2588
2589=== Other data types
2590
2591This section describes operations on some of Scheme's non-numeric data
2592types: booleans, pairs, lists, symbols, characters, strings and
2593vectors.
2594
2595==== Booleans
2596
2597The standard boolean objects for true and false are written as #t and #f.
2598What really matters, though, are the objects that the Scheme
2599conditional expressions (if, cond, and, or, do) treat as true or false.
2600The phrase "a true value" (or sometimes just "true") means any
2601object treated as true by the conditional expressions, and the phrase
2602"a false value" (or "false") means any object treated as false by
2603the conditional expressions.
2604
2605Of all the standard Scheme values, only #f counts as false in
2606conditional expressions. Except for #f, all standard Scheme values,
2607including #t, pairs, the empty list, symbols, numbers, strings,
2608vectors, and procedures, count as true.
2609
2610Note:   Programmers accustomed to other dialects of Lisp should be
2611aware that Scheme distinguishes both #f and the empty list from the
2612symbol nil.
2613
2614Boolean constants evaluate to themselves, so they do not need to be
2615quoted in programs.
2616
2617 #t                ===>  #t
2618 #f                ===>  #f
2619 '#f               ===>  #f
2620
2621<procedure>(not obj)</procedure><br>
2622
2623Not returns #t if obj is false, and returns #f otherwise.
2624
2625 (not #t)           ===>  #f
2626 (not 3)            ===>  #f
2627 (not (list 3))     ===>  #f
2628 (not #f)           ===>  #t
2629 (not '())          ===>  #f
2630 (not (list))       ===>  #f
2631 (not 'nil)         ===>  #f
2632
2633<procedure>(boolean? obj)</procedure><br>
2634
2635Boolean? returns #t if obj is either #t or #f and returns #f otherwise.
2636
2637 (boolean? #f)                 ===>  #t
2638 (boolean? 0)                  ===>  #f
2639 (boolean? '())                ===>  #f
2640
2641<procedure>(boolean=? boolean[1] boolean[2] boolean[3] ...)</procedure>
2642
2643Returns #t if all the arguments are #t or all are #f.
2644
2645==== Pairs and lists
2646
2647A pair (sometimes called a dotted pair) is a record structure with two
2648fields called the car and cdr fields (for historical reasons). Pairs
2649are created by the procedure cons. The car and cdr fields are accessed
2650by the procedures car and cdr. The car and cdr fields are assigned by
2651the procedures set-car! and set-cdr!.
2652
2653Pairs are used primarily to represent lists. A list can be defined
2654recursively as either the empty list or a pair whose cdr is a list.
2655More precisely, the set of lists is defined as the smallest set X such
2656that
2657
2658*   The empty list is in X.
2659*   If list is in X, then any pair whose cdr field contains list is
2660    also in X.
2661
2662The objects in the car fields of successive pairs of a list are the
2663elements of the list. For example, a two-element list is a pair whose
2664car is the first element and whose cdr is a pair whose car is the
2665second element and whose cdr is the empty list. The length of a list is
2666the number of elements, which is the same as the number of pairs.
2667
2668The empty list is a special object of its own type (it is not a pair);
2669it has no elements and its length is zero.
2670
2671Note:   The above definitions imply that all lists have finite
2672length and are terminated by the empty list.
2673
2674The most general notation (external representation) for Scheme pairs is
2675the "dotted" notation (c[1] . c[2]) where c[1] is the value of the
2676car field and c[2] is the value of the cdr field. For example (4 . 5)
2677is a pair whose car is 4 and whose cdr is 5. Note that (4 . 5) is the
2678external representation of a pair, not an expression that evaluates to
2679a pair.
2680
2681A more streamlined notation can be used for lists: the elements of the
2682list are simply enclosed in parentheses and separated by spaces. The
2683empty list is written () . For example,
2684
2685 (a b c d e)
2686
2687and
2688
2689 (a . (b . (c . (d . (e . ())))))
2690
2691are equivalent notations for a list of symbols.
2692
2693A chain of pairs not ending in the empty list is called an improper
2694list. Note that an improper list is not a list. The list and dotted
2695notations can be combined to represent improper lists:
2696
2697 (a b c . d)
2698
2699is equivalent to
2700
2701 (a . (b . (c . d)))
2702
2703Whether a given pair is a list depends upon what is stored in the cdr
2704field. When the set-cdr! procedure is used, an object can be a list one
2705moment and not the next:
2706
2707 (define x (list 'a 'b 'c))
2708 (define y x)
2709 y                               ===>  (a b c)
2710 (list? y)                       ===>  #t
2711 (set-cdr! x 4)                  ===>  unspecified
2712 x                               ===>  (a . 4)
2713 (eqv? x y)                      ===>  #t
2714 y                               ===>  (a . 4)
2715 (list? y)                       ===>  #f
2716 (set-cdr! x x)                  ===>  unspecified
2717 (list? x)                       ===>  #f
2718
2719Within literal expressions and representations of objects read by the
2720read procedure, the forms '<datum>, `<datum>, ,<datum>, and ,@<datum>
2721denote two-element lists whose first elements are the symbols quote,
2722quasiquote, unquote, and unquote-splicing, respectively. The second
2723element in each case is <datum>. This convention is supported so that
2724arbitrary Scheme programs may be represented as lists. That is,
2725according to Scheme's grammar, every <expression> is also a <datum>.
2726Among other things, this permits the use of the read procedure to
2727parse Scheme programs.
2728
2729<procedure>(pair? obj)</procedure><br>
2730
2731Pair? returns #t if obj is a pair, and otherwise returns #f.
2732
2733 (pair? '(a . b))                ===>  #t
2734 (pair? '(a b c))                ===>  #t
2735 (pair? '())                     ===>  #f
2736 (pair? '#(a b))                 ===>  #f
2737
2738<procedure>(cons obj[1] obj[2])</procedure><br>
2739
2740Returns a newly allocated pair whose car is obj[1] and whose cdr is
2741obj[2]. The pair is guaranteed to be different (in the sense of eqv?)
2742from every existing object.
2743
2744 (cons 'a '())                   ===>  (a)
2745 (cons '(a) '(b c d))            ===>  ((a) b c d)
2746 (cons "a" '(b c))               ===>  ("a" b c)
2747 (cons 'a 3)                     ===>  (a . 3)
2748 (cons '(a b) 'c)                ===>  ((a b) . c)
2749
2750<procedure>(car pair)</procedure><br>
2751
2752Returns the contents of the car field of pair. Note that it is an error
2753to take the car of the empty list.
2754
2755 (car '(a b c))                  ===>  a
2756 (car '((a) b c d))              ===>  (a)
2757 (car '(1 . 2))                  ===>  1
2758 (car '())                       ===>  error
2759
2760<procedure>(cdr pair)</procedure><br>
2761
2762Returns the contents of the cdr field of pair. Note that it is an error
2763to take the cdr of the empty list.
2764
2765 (cdr '((a) b c d))              ===>  (b c d)
2766 (cdr '(1 . 2))                  ===>  2
2767 (cdr '())                       ===>  error
2768
2769<procedure>(set-car! pair obj)</procedure><br>
2770
2771Stores obj in the car field of pair. The value returned by set-car! is
2772unspecified.
2773
2774 (define (f) (list 'not-a-constant-list))
2775 (define (g) '(constant-list))
2776 (set-car! (f) 3)                     ===>  unspecified
2777 (set-car! (g) 3)                     ===>  error
2778
2779<procedure>(set-cdr! pair obj)</procedure><br>
2780
2781Stores obj in the cdr field of pair. The value returned by set-cdr! is
2782unspecified.
2783
2784<procedure>(null? obj)</procedure><br>
2785
2786Returns #t if obj is the empty list, otherwise returns #f.
2787
2788<procedure>(list? obj)</procedure><br>
2789
2790Returns #t if obj is a list, otherwise returns #f. By definition, all
2791lists have finite length and are terminated by the empty list.
2792
2793 (list? '(a b c))             ===>  #t
2794 (list? '())                  ===>  #t
2795 (list? '(a . b))             ===>  #f
2796 (let ((x (list 'a)))
2797   (set-cdr! x x)
2798   (list? x))                 ===>  #f
2799
2800<procedure>(make-list k [fill])</procedure>
2801
2802Returns a newly allocated list of k elements. If a second argument is given, then each element is initialized to {{fill}}. Otherwise the initial contents of each element is unspecified.
2803
2804 (make-list 2 3)    ==>   (3 3)
2805
2806<procedure>(list obj ...)</procedure><br>
2807
2808Returns a newly allocated list of its arguments.
2809
2810 (list 'a (+ 3 4) 'c)                    ===>  (a 7 c)
2811 (list)                                  ===>  ()
2812
2813<procedure>(length list)</procedure><br>
2814
2815Returns the length of list.
2816
2817 (length '(a b c))                       ===>  3
2818 (length '(a (b) (c d e)))               ===>  3
2819 (length '())                            ===>  0
2820
2821<procedure>(append list ...)</procedure><br>
2822
2823Returns a list consisting of the elements of the first list followed by
2824the elements of the other lists.
2825
2826 (append '(x) '(y))                      ===>  (x y)
2827 (append '(a) '(b c d))                  ===>  (a b c d)
2828 (append '(a (b)) '((c)))                ===>  (a (b) (c))
2829
2830The resulting list is always newly allocated, except that it shares
2831structure with the last list argument. The last argument may actually
2832be any object; an improper list results if the last argument is not a
2833proper list.
2834
2835 (append '(a b) '(c . d))                ===>  (a b c . d)
2836 (append '() 'a)                         ===>  a
2837
2838<procedure>(reverse list)</procedure><br>
2839
2840Returns a newly allocated list consisting of the elements of list in
2841reverse order.
2842
2843 (reverse '(a b c))                      ===>  (c b a)
2844 (reverse '(a (b c) d (e (f))))
2845                 ===>  ((e (f)) d (b c) a)
2846
2847<procedure>(list-tail list k)</procedure><br>
2848
2849Returns the sublist of list obtained by omitting the first k elements.
2850It is an error if list has fewer than k elements. List-tail could be
2851defined by
2852
2853 (define list-tail
2854   (lambda (x k)
2855     (if (zero? k)
2856         x
2857         (list-tail (cdr x) (- k 1)))))
2858
2859<procedure>(list-ref list k)</procedure><br>
2860
2861Returns the kth element of list. (This is the same as the car of
2862(list-tail list k).) It is an error if list has fewer than k elements.
2863
2864 (list-ref '(a b c d) 2)                ===>  c
2865 (list-ref '(a b c d)
2866           (inexact->exact (round 1.8)))
2867                 ===>  c
2868
2869<procedure>(list-set! list k obj)</procedure>
2870
2871It is an error if k is not a valid index of list.
2872
2873The {{list-set!}} procedure stores obj in element k of list.
2874
2875 (let ((ls (list 'one 'two 'five!)))
2876   (list-set! ls 2 'three)
2877   ls)
2878 ==>  (one two three)
2879
2880 (list-set! '(0 1 2) 1 "oops")
2881 ==> error  ; constant list
2882
2883<procedure>(memq obj list)</procedure><br>
2884<procedure>(memv obj list)</procedure><br>
2885<procedure>(member obj list [compare])</procedure><br>
2886
2887These procedures return the first sublist of list whose car is obj,
2888where the sublists of list are the non-empty lists returned by
2889{{(list-tail list k)}} for k less than the length of list. If obj does not
2890occur in list, then #f (not the empty list) is returned. {{memq}} uses {{eq?}}
2891to compare obj with the elements of list, while {{memv}} uses {{eqv?}} and
2892member {{compare}} if given, and {{equal?}} otherwise.
2893
2894 (memq 'a '(a b c))                      ===>  (a b c)
2895 (memq 'b '(a b c))                      ===>  (b c)
2896 (memq 'a '(b c d))                      ===>  #f
2897 (memq (list 'a) '(b (a) c))             ===>  #f
2898 (member (list 'a)
2899         '(b (a) c))                     ===>  ((a) c)
2900 (memq 101 '(100 101 102))               ===>  unspecified
2901 (memv 101 '(100 101 102))               ===>  (101 102)
2902
2903<procedure>(assq obj alist)</procedure><br>
2904<procedure>(assv obj alist)</procedure><br>
2905<procedure>(assoc obj alist [compare])</procedure><br>
2906
2907Alist (for "association list") must be a list of pairs. These
2908procedures find the first pair in alist whose car field is obj, and
2909returns that pair. If no pair in alist has obj as its car, then #f (not
2910the empty list) is returned. {{assq}} uses {{eq?}} to compare obj with the car
2911fields of the pairs in alist, while {{assv}} uses {{eqv?}} and {{assoc}} uses
2912{{compare}}, if given, otherwise {{equal?}}.
2913
2914 (define e '((a 1) (b 2) (c 3)))
2915 (assq 'a e)             ===>  (a 1)
2916 (assq 'b e)             ===>  (b 2)
2917 (assq 'd e)             ===>  #f
2918 (assq (list 'a) '(((a)) ((b)) ((c))))
2919                         ===>  #f
2920 (assoc (list 'a) '(((a)) ((b)) ((c))))
2921                                    ===>  ((a))
2922 (assq 5 '((2 3) (5 7) (11 13)))
2923                                    ===>  unspecified
2924 (assv 5 '((2 3) (5 7) (11 13)))
2925                                    ===>  (5 7)
2926
2927Rationale:   Although they are ordinarily used as predicates, memq,
2928memv, member, assq, assv, and assoc do not have question marks in
2929their names because they return useful values rather than just #t
2930or #f.
2931
2932<procedure>(list-copy obj)</procedure>
2933
2934Returns a newly allocated copy of the given obj if it is a list. Only the pairs themselves are copied; the cars of the result are the same (in the sense of {{eqv?}}) as the cars of list. If obj is an improper list, so is the result, and the final cdrs are the same in
2935the sense of {{eqv?}}. An obj which is not a list is returned unchanged. It is an error if
2936obj is a circular list.
2937
2938 (define a '(1 8 2 8)) ; a may be immutable
2939 (define b (list-copy a))
2940 (set-car! b 3)        ; b is mutable
2941 b  ==> (3 8 2 8)
2942 a  ==> (1 8 2 8)
2943
2944==== Symbols
2945
2946Symbols are objects whose usefulness rests on the fact that two symbols
2947are identical (in the sense of eqv?) if and only if their names are
2948spelled the same way. This is exactly the property needed to represent
2949identifiers in programs, and so most implementations of Scheme use them
2950internally for that purpose. Symbols are useful for many other
2951applications; for instance, they may be used the way enumerated values
2952are used in Pascal.
2953
2954The rules for writing a symbol are exactly the same as the rules for
2955writing an identifier.
2956
2957It is guaranteed that any symbol that has been returned as part of a
2958literal expression, or read using the read procedure, and subsequently
2959written out using the write procedure, will read back in as the
2960identical symbol (in the sense of eqv?). The string->symbol procedure,
2961however, can create symbols for which this write/read invariance may
2962not hold because their names contain special characters or letters in
2963the non-standard case.
2964
2965Note:   Some implementations of Scheme have a feature known as
2966"slashification" in order to guarantee write/read invariance for
2967all symbols, but historically the most important use of this
2968feature has been to compensate for the lack of a string data type.
2969
2970Some implementations also have "uninterned symbols", which defeat
2971write/read invariance even in implementations with slashification,
2972and also generate exceptions to the rule that two symbols are the
2973same if and only if their names are spelled the same.
2974
2975<procedure>(symbol? obj)</procedure><br>
2976
2977Returns #t if obj is a symbol, otherwise returns #f.
2978
2979 (symbol? 'foo)                  ===>  #t
2980 (symbol? (car '(a b)))          ===>  #t
2981 (symbol? "bar")                 ===>  #f
2982 (symbol? 'nil)                  ===>  #t
2983 (symbol? '())                   ===>  #f
2984 (symbol? #f)                    ===>  #f
2985
2986<procedure>(symbol=? symbol[1] symbol[2] symbol[3] ...)</procedure>
2987
2988Returns #t if all the arguments all have the same names in the sense of {{string=?}}.
2989
2990Note: The definition above assumes that none of the arguments are uninterned symbols.
2991
2992<procedure>(symbol->string symbol)</procedure><br>
2993
2994Returns the name of symbol as a string. If the symbol was part of an
2995object returned as the value of a literal expression (see
2996"[[#literal-expressions|literal expressions]]") or by a call to the
2997read procedure, and its name contains alphabetic characters, then the
2998string returned will contain characters in the implementation's
2999preferred standard case -- some implementations will prefer upper
3000case, others lower case. If the symbol was returned by string->symbol,
3001the case of characters in the string returned will be the same as the
3002case in the string that was passed to string->symbol.  It is an error
3003to apply mutation procedures like string-set! to strings returned by
3004this procedure.
3005
3006The following examples assume that the implementation's standard case
3007is lower case:
3008
3009 (symbol->string 'flying-fish)
3010                                           ===>  "flying-fish"
3011 (symbol->string 'Martin)                  ===>  "martin"
3012 (symbol->string
3013    (string->symbol "Malvina"))
3014                                           ===>  "Malvina"
3015
3016<procedure>(string->symbol string)</procedure><br>
3017
3018Returns the symbol whose name is string. This procedure can create
3019symbols with names containing special characters or letters in the
3020non-standard case, but it is usually a bad idea to create such symbols
3021because in some implementations of Scheme they cannot be read as
3022themselves. See symbol->string.
3023
3024The following examples assume that the implementation's standard case
3025is lower case:
3026
3027 (eq? 'mISSISSIppi 'mississippi)
3028                 ===>  #t
3029 (string->symbol "mISSISSIppi")
3030                 ===>  the symbol with name "mISSISSIppi"
3031 (eq? 'bitBlt (string->symbol "bitBlt"))
3032                 ===>  #f
3033 (eq? 'JollyWog
3034      (string->symbol
3035        (symbol->string 'JollyWog)))
3036                 ===>  #t
3037 (string=? "K. Harper, M.D."
3038           (symbol->string
3039             (string->symbol "K. Harper, M.D.")))
3040                 ===>  #t
3041
3042==== Characters
3043
3044Characters are objects that represent printed characters such as
3045letters and digits. Characters are written using the notation #\
3046<character> or #\<character name>. For example:
3047
3048Characters are written using the notation {{#\<character>}} or {{#\<character name>}}
3049or {{#\x<hex scalar value>}}.
3050
3051The following character names must be supported by all implementations with the
3052given values. Implementations may add other names provided they cannot be
3053interpreted as hex scalar values preceded by x.
3054
3055   #\alarm     ; U+0007
3056   #\backspace ; U+0008
3057   #\delete    ; U+007F
3058   #\escape    ; U+001B
3059   #\newline   ; the linefeed character, U+000A
3060   #\null      ; the null character, U+0000
3061   #\return    ; the return character, U+000D
3062   #\space     ; the preferred way to write a space
3063   #\tab       ; the tab character, U+0009
3064
3065Here are some additional examples:
3066
3067 #\a       ; lower case letter
3068 #\A       ; upper case letter
3069 #\(       ; left parenthesis
3070 #\        ; the space character
3071 #\space   ; the preferred way to write a space
3072 #\newline ; the newline character
3073
3074Case is significant in #\<character>, but not in #\<character name>. If
3075<character> in #\<character> is alphabetic, then the character
3076following <character> must be a delimiter character such as a space or
3077parenthesis. This rule resolves the ambiguous case where, for example,
3078the sequence of characters "#\space" could be taken to be either a
3079representation of the space character or a representation of the
3080character "#\s" followed by a representation of the symbol "pace."
3081
3082Characters written in the #\ notation are self-evaluating. That is,
3083they do not have to be quoted in programs. Some of the procedures that
3084operate on characters ignore the difference between upper case and
3085lower case. The procedures that ignore case have "-ci" (for "case
3086insensitive") embedded in their names.
3087
3088<procedure>(char? obj)</procedure><br>
3089
3090Returns #t if obj is a character, otherwise returns #f.
3091
3092<procedure>(char=? char[1] char[2] char[3] ...)</procedure><br>
3093<procedure>(char<? char[1] char[2] char[3] ...)</procedure><br>
3094<procedure>(char>? char[1] char[2] char[3] ...)</procedure><br>
3095<procedure>(char<=? char[1] char[2] char[3] ...)</procedure><br>
3096<procedure>(char>=? char[1] char[2] char[3] ...)</procedure><br>
3097
3098These procedures impose a total ordering on the set of characters. It
3099is guaranteed that under this ordering:
3100
3101*   The upper case characters are in order. For example, (char<? #\A #\
3102    B) returns #t.
3103*   The lower case characters are in order. For example, (char<? #\a #\
3104    b) returns #t.
3105*   The digits are in order. For example, (char<? #\0 #\9) returns #t.
3106*   Either all the digits precede all the upper case letters, or vice
3107    versa.
3108*   Either all the digits precede all the lower case letters, or vice
3109    versa.
3110
3111Some implementations may generalize these procedures to take more than
3112two arguments, as with the corresponding numerical predicates.
3113
3114<procedure>(char-ci=? char[1] char[2] char[3] ...)</procedure><br>
3115<procedure>(char-ci<? char[1] char[2] char[3] ...)</procedure><br>
3116<procedure>(char-ci>? char[1] char[2] char[3] ...)</procedure><br>
3117<procedure>(char-ci<=? char[1] char[2] char[3] ...)</procedure><br>
3118<procedure>(char-ci>=? char[1] char[2] char[3] ...)</procedure><br>
3119
3120These procedures are similar to char=? et cetera, but they treat upper
3121case and lower case letters as the same. For example, (char-ci=? #\A #\
3122a) returns #t. Some implementations may generalize these procedures to
3123take more than two arguments, as with the corresponding numerical
3124predicates.
3125
3126<procedure>(char-alphabetic? char)</procedure><br>
3127<procedure>(char-numeric? char)</procedure><br>
3128<procedure>(char-whitespace? char)</procedure><br>
3129<procedure>(char-upper-case? letter)</procedure><br>
3130<procedure>(char-lower-case? letter)</procedure><br>
3131
3132These procedures return #t if their arguments are alphabetic, numeric,
3133whitespace, upper case, or lower case characters, respectively,
3134otherwise they return #f. The following remarks, which are specific to
3135the ASCII character set, are intended only as a guide: The alphabetic
3136characters are the 52 upper and lower case letters. The numeric
3137characters are the ten decimal digits. The whitespace characters are
3138space, tab, line feed, form feed, and carriage return.
3139
3140<procedure>(char->integer char)</procedure><br>
3141<procedure>(integer->char n)</procedure><br>
3142
3143Given a character, char->integer returns an exact integer
3144representation of the character. Given an exact integer that is the
3145image of a character under char->integer, integer->char returns that
3146character. These procedures implement order-preserving isomorphisms
3147between the set of characters under the char<=? ordering and some
3148subset of the integers under the <= ordering. That is, if
3149
3150 (char<=? a b) ===> #t  and  (<= x y) ===> #t
3151
3152and x and y are in the domain of integer->char, then
3153
3154 (<= (char->integer a)
3155     (char->integer b))                  ===>  #t
3156 
3157 (char<=? (integer->char x)
3158          (integer->char y))             ===>  #t
3159
3160Note that {{integer->char}} does currently not detect
3161a negative argument and will quietly convert {{-1}} to
3162{{#x1ffff}} in CHICKEN.
3163
3164==== Strings
3165
3166Strings are sequences of characters. Strings are written as sequences of
3167characters enclosed within quotation marks ("). Within a string literal,
3168various escape sequences represent characters other than themselves. Escape
3169sequences always start with a backslash (\):
3170
3171* \a : alarm, U+0007
3172
3173* \b : backspace, U+0008
3174
3175* \t : character tabulation, U+0009
3176
3177* \n : linefeed, U+000A
3178
3179* \r : return, U+000D
3180
3181* \" : double quote, U+0022
3182
3183* \\ : backslash, U+005C
3184
3185* \| : vertical line, U+007C
3186
3187* \<intraline whitespace>*<line ending> <intraline whitespace>* : nothing
3188
3189* \x<hex scalar value>; : specified character (note the terminating
3190    semi-colon).
3191
3192The result is unspecified if any other character in a string occurs after a
3193backslash.
3194
3195Except for a line ending, any character outside of an escape sequence stands
3196for itself in the string literal. A line ending which is preceded by \
3197<intraline whitespace> expands to nothing (along with any trailing intraline
3198whitespace), and can be used to indent strings for improved legibility. Any
3199other line ending has the same effect as inserting a \n character into the
3200string.
3201
3202Examples:
3203
3204 "The word \"recursion\" has many meanings."
3205 "Another example:\ntwo lines of text"
3206 "Here's text \
3207    containing just one line"
3208 "\x03B1; is named GREEK SMALL LETTER ALPHA."
3209
3210The length of a string is the
3211number of characters that it contains. This number is an exact, non-negative
3212integer that is fixed when the string is created. The valid indexes of a string
3213are the exact non-negative integers less than the length of the string. The
3214first character of a string has index 0, the second has index 1, and so on.
3215
3216<procedure>(string? obj)</procedure><br>
3217
3218Returns #t if obj is a string, otherwise returns #f.
3219
3220<procedure>(make-string k)</procedure><br>
3221<procedure>(make-string k char)</procedure><br>
3222
3223Make-string returns a newly allocated string of length k. If char is
3224given, then all elements of the string are initialized to char,
3225otherwise the contents of the string are unspecified.
3226
3227<procedure>(string char ...)</procedure><br>
3228
3229Returns a newly allocated string composed of the arguments.
3230
3231<procedure>(string-length string)</procedure><br>
3232
3233Returns the number of characters in the given string.
3234
3235<procedure>(string-ref string k)</procedure><br>
3236
3237k must be a valid index of string. String-ref returns character k of
3238string using zero-origin indexing.
3239
3240<procedure>(string-set! string k char)</procedure><br>
3241
3242k must be a valid index of string. String-set! stores char in element k
3243of string and returns an unspecified value.
3244
3245 (define (f) (make-string 3 #\*))
3246 (define (g) "***")
3247 (string-set! (f) 0 #\?)          ===>  unspecified
3248 (string-set! (g) 0 #\?)          ===>  error
3249 (string-set! (symbol->string 'immutable)
3250              0
3251              #\?)          ===>  error
3252
3253<procedure>(string=? string[1] string[2] string[3] ...)</procedure><br>
3254
3255Returns #t if the two strings are the same length and contain the same
3256characters in the same positions, otherwise returns #f.
3257
3258<procedure>(string<? string[1] string[2] string[3] ...)</procedure><br>
3259<procedure>(string>? string[1] string[2] string[3] ...)</procedure><br>
3260<procedure>(string<=? string[1] string[2] string[3] ...)</procedure><br>
3261<procedure>(string>=? string[1] string[2] string[3] ...)</procedure><br>
3262
3263These procedures are the lexicographic extensions to strings of the
3264corresponding orderings on characters. For example, string<? is the
3265lexicographic ordering on strings induced by the ordering char<? on
3266characters. If two strings differ in length but are the same up to the
3267length of the shorter string, the shorter string is considered to be
3268lexicographically less than the longer string.
3269
3270<procedure>(substring string start [end])</procedure><br>
3271
3272String must be a string, and start and end must be exact integers
3273satisfying
3274
3275 0 <= start <= end <= (string-length string)
3276
3277Substring returns a newly allocated string formed from the characters
3278of string beginning with index start (inclusive) and ending with index
3279end (exclusive). The {{end}} argument is optional and defaults to the
3280length of the string, this is a non-standard extension in CHICKEN.
3281
3282<procedure>(string-append string ...)</procedure><br>
3283
3284Returns a newly allocated string whose characters form the
3285concatenation of the given strings.
3286
3287<procedure>(string->list string [start [end]])</procedure><br>
3288<procedure>(list->string list)</procedure><br>
3289
3290String->list returns a newly allocated list of the characters that make
3291up the given string between start and end. List->string returns a newly allocated string
3292formed from the characters in the list list, which must be a list of
3293characters. String->list and list->string are inverses so far as equal?
3294is concerned.
3295
3296<procedure>(string-copy string [start [end]])</procedure><br>
3297
3298Returns a newly allocated copy of the given string.
3299
3300<procedure>(string-copy! to at from [start [end]])</procedure>
3301
3302It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (string-length to) at)}} is less than {{(- end start)}}.
3303
3304Copies the characters of string from between start and end to string to, starting at
3305at. The order in which characters are copied is unspecified, except that if the
3306source and destination overlap, copying takes place as if the source is first
3307copied into a temporary string and then into the destination. This can be
3308achieved without allocating storage by making sure to copy in the correct
3309direction in such circumstances.
3310
3311 (define a "12345")
3312 (define b (string-copy "abcde"))
3313 (string-copy! b 1 a 0 2)
3314 b  ==> "a12de"
3315
3316<procedure>(string-fill! string char +#!optional start end)</procedure><br>
3317
3318Stores char in every element of the given string and returns an
3319unspecified value. The optional start and end arguments specify
3320the part of the string to be filled and default to the complete string.
3321
3322==== Vectors
3323
3324Vectors are heterogenous structures whose elements are indexed by
3325integers. A vector typically occupies less space than a list of the
3326same length, and the average time required to access a randomly chosen
3327element is typically less for the vector than for the list.
3328
3329The length of a vector is the number of elements that it contains. This
3330number is a non-negative integer that is fixed when the vector is
3331created. The valid indexes of a vector are the exact non-negative
3332integers less than the length of the vector. The first element in a
3333vector is indexed by zero, and the last element is indexed by one less
3334than the length of the vector.
3335
3336Vectors are written using the notation #(obj ...). For example, a
3337vector of length 3 containing the number zero in element 0, the list (2
33382 2 2) in element 1, and the string "Anna" in element 2 can be written
3339as following:
3340
3341 #(0 (2 2 2 2) "Anna")
3342
3343Vector constants are self-evaluating, so they do not need
3344to be quoted in programs.
3345
3346<procedure>(vector? obj)</procedure><br>
3347
3348Returns #t if obj is a vector, otherwise returns #f.
3349
3350<procedure>(make-vector k)</procedure><br>
3351<procedure>(make-vector k fill)</procedure><br>
3352
3353Returns a newly allocated vector of k elements. If a second argument is
3354given, then each element is initialized to fill. Otherwise the initial
3355contents of each element is unspecified.
3356
3357<procedure>(vector obj ...)</procedure><br>
3358
3359Returns a newly allocated vector whose elements contain the given
3360arguments. Analogous to list.
3361
3362 (vector 'a 'b 'c)                       ===>  #(a b c)
3363
3364<procedure>(vector-length vector)</procedure><br>
3365
3366Returns the number of elements in vector as an exact integer.
3367
3368<procedure>(vector-ref vector k)</procedure><br>
3369
3370k must be a valid index of vector. Vector-ref returns the contents of
3371element k of vector.
3372
3373 (vector-ref '#(1 1 2 3 5 8 13 21)
3374             5)
3375                 ===>  8
3376 (vector-ref '#(1 1 2 3 5 8 13 21)
3377             (let ((i (round (* 2 (acos -1)))))
3378               (if (inexact? i)
3379                   (inexact->exact i)
3380                   i)))
3381                 ===> 13
3382
3383<procedure>(vector-set! vector k obj)</procedure><br>
3384
3385k must be a valid index of vector. Vector-set! stores obj in element k
3386of vector. The value returned by vector-set! is unspecified.
3387
3388 (let ((vec (vector 0 '(2 2 2 2) "Anna")))
3389   (vector-set! vec 1 '("Sue" "Sue"))
3390   vec)
3391                 ===>  #(0 ("Sue" "Sue") "Anna")
3392
3393 (vector-set! '#(0 1 2) 1 "doe")
3394                 ===>  error  ; constant vector
3395
3396<procedure>(vector->list vector [start [end]])</procedure><br>
3397<procedure>(list->vector list)</procedure><br>
3398
3399Vector->list returns a newly allocated list of the objects contained in
3400the elements of vector. List->vector returns a newly created vector
3401initialized to the elements of the list list.
3402
3403 (vector->list '#(dah dah didah))
3404                 ===>  (dah dah didah)
3405 (list->vector '(dididit dah))
3406                 ===>  #(dididit dah)
3407
3408<procedure>(vector->string vector [start [end]])</procedure><br>
3409<procedure>(string->vector string [start [end]])</procedure>
3410
3411It is an error if any element of vector between start and end is not a character.
3412
3413The vector->string procedure returns a newly allocated string of the objects
3414contained in the elements of vector between start and end. The string->vector procedure returns a newly created vector initialized to
3415the elements of the string string between start and end.
3416
3417In both procedures, order is preserved.
3418
3419 (string->vector "ABC")   ==>   #(#\A #\B #\C)
3420 (vector->string #(#\1 #\2 #\3))  ==> "123"
3421
3422<procedure>(vector-copy vector [start [end]])</procedure>
3423
3424Returns a newly allocated copy of the elements of the given vector between
3425start and end. The elements of the new vector are the same (in the sense of eqv?) as the
3426elements of the old.
3427
3428 (define a #(1 8 2 8)) ; a may be immutable
3429 (define b (vector-copy a))
3430 (vector-set! b 0 3)   ; b is mutable
3431 b  ==> #(3 8 2 8)
3432 (define c (vector-copy b 1 3))
3433 c  ==> #(8 2)
3434
3435<procedure>(vector-copy! to at from [start [end]])</procedure>
3436
3437It is an error if at is less than zero or greater than the length of to. It is also an error if {{(- (vector-length to) at)}} is less than {{(- end start)}}.
3438
3439Copies the elements of vector from between start and end to vector to, starting at
3440at. The order in which elements are copied is unspecified, except that if the
3441source and destination overlap, copying takes place as if the source is first
3442copied into a temporary vector and then into the destination. This can be
3443achieved without allocating storage by making sure to copy in the correct
3444direction in such circumstances.
3445
3446 (define a (vector 1 2 3 4 5))
3447 (define b (vector 10 20 30 40 50))
3448 (vector-copy! b 1 a 0 2)
3449 b  ==> #(10 1 2 40 50)
3450
3451<procedure>(vector-append vector ....)</procedure>
3452
3453Returns a newly allocated vector whose elements are the concatenation of the
3454elements of the given vectors.
3455
3456 (vector-append #(a b c) #(d e f)) ==> #(a b c d e f)
3457
3458<procedure>(vector-fill! vector fill [start [end]])</procedure>
3459
3460The vector-fill! procedure stores fill in the elements of vector between start and
3461end.
3462
3463 (define a (vector 1 2 3 4 5))
3464 (vector-fill! a 'smash 2 4)
3465 a ==>#(1 2 smash smash 5)
3466
3467====  Bytevectors
3468
3469Bytevectors represent blocks of binary data. They are fixed-length sequences of
3470bytes, where a byte is an exact integer in the range from 0 to 255 inclusive. A
3471bytevector is typically more space-efficient than a vector containing the same
3472values.
3473
3474See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
3475information. {{(scheme base)}} re-exports all R7RS-specific procedures from
3476that module.
3477
3478=== Control features
3479
3480This chapter describes various primitive procedures which control the
3481flow of program execution in special ways. The procedure? predicate is
3482also described here.
3483
3484<procedure>(procedure? obj)</procedure><br>
3485
3486Returns #t if obj is a procedure, otherwise returns #f.
3487
3488 (procedure? car)                    ===>  #t
3489 (procedure? 'car)                   ===>  #f
3490 (procedure? (lambda (x) (* x x)))
3491                                     ===>  #t
3492 (procedure? '(lambda (x) (* x x)))
3493                                     ===>  #f
3494 (call-with-current-continuation procedure?)
3495                                     ===>  #t
3496
3497<procedure>(apply proc arg[1] ... args)</procedure><br>
3498
3499Proc must be a procedure and args must be a list. Calls proc with the
3500elements of the list (append (list arg[1] ...) args) as the actual
3501arguments.
3502
3503 (apply + (list 3 4))                      ===>  7
3504 
3505 (define compose
3506   (lambda (f g)
3507     (lambda args
3508       (f (apply g args)))))
3509 
3510 ((compose sqrt *) 12 75)                      ===>  30
3511
3512<procedure>(map proc list[1] list[2] ...)</procedure><br>
3513
3514The lists must be lists, and proc must be a procedure taking as many
3515arguments as there are lists and returning a single value. Map applies
3516proc element-wise to the elements of the lists and returns a list of
3517the results, in order. The dynamic order in which proc is applied to
3518the elements of the lists is unspecified.
3519
3520Like in SRFI-1, this procedure allows the arguments to be of unequal
3521length; it terminates when the shortest list runs out.  This is a
3522CHICKEN extension to R7RS.
3523
3524 (map cadr '((a b) (d e) (g h)))
3525                 ===>  (b e h)
3526 
3527 (map (lambda (n) (expt n n))
3528      '(1 2 3 4 5))
3529                 ===>  (1 4 27 256 3125)
3530 
3531 (map + '(1 2 3) '(4 5 6))                 ===>  (5 7 9)
3532 
3533 (let ((count 0))
3534   (map (lambda (ignored)
3535          (set! count (+ count 1))
3536          count)
3537        '(a b)))                         ===>  (1 2) or (2 1)
3538
3539<procedure>(string-map proc string[1] string[2] ...)</procedure>
3540
3541It is an error if proc does not accept as many arguments as there are strings and return a single character.
3542
3543The string-map procedure applies proc element-wise to the elements of the
3544strings and returns a string of the results, in order. If more than one
3545string is given and not all strings have the same length, string-map terminates
3546when the shortest string runs out. The dynamic order in which
3547proc is applied to the elements of the
3548strings is unspecified. If multiple returns occur from string-map, the values
3549returned by earlier returns are not mutated.
3550
3551 (string-map char-foldcase "AbdEgH") ==> "abdegh"
3552
3553 (string-map
3554  (lambda (c)
3555    (integer->char (+ 1 (char->integer c))))
3556  "HAL")                ==> "IBM"
3557
3558 (string-map
3559  (lambda (c k)
3560    ((if (eqv? k #\u) char-upcase char-downcase)
3561     c))
3562  "studlycaps xxx"
3563  "ululululul")         ==> "StUdLyCaPs"
3564
3565<procedure>(vector-map proc vector[1] vector[2] ...)</procedure>
3566
3567It is an error if proc does not accept as many arguments as there are vectors and return a single value.
3568
3569The vector-map procedure applies proc element-wise to the elements of the
3570vectors and returns a vector of the results, in order. If more than one
3571vector is given and not all vectors have the same length, vector-map terminates
3572when the shortest vector runs out. The dynamic order in which
3573proc is applied to the elements of the
3574vectors is unspecified. If multiple returns occur from vector-map, the values
3575returned by earlier returns are not mutated.
3576
3577 (vector-map cadr '#((a b) (d e) (g h)))
3578 ==> #(b e h)
3579
3580 (vector-map (lambda (n) (expt n n))
3581             '#(1 2 3 4 5))
3582 ==> #(1 4 27 256 3125)
3583
3584 (vector-map + '#(1 2 3) '#(4 5 6 7))
3585 ==>  #(5 7 9)
3586
3587 (let ((count 0))
3588   (vector-map
3589    (lambda (ignored)
3590      (set! count (+ count 1))
3591      count)
3592    '#(a b)))                      ==>  #(1 2) or #(2 1)
3593
3594<procedure>(for-each proc list[1] list[2] ...)</procedure><br>
3595
3596The arguments to for-each are like the arguments to map, but for-each
3597calls proc for its side effects rather than for its values. Unlike map,
3598for-each is guaranteed to call proc on the elements of the lists in
3599order from the first element(s) to the last, and the value returned by
3600for-each is unspecified.
3601
3602 (let ((v (make-vector 5)))
3603   (for-each (lambda (i)
3604               (vector-set! v i (* i i)))
3605             '(0 1 2 3 4))
3606   v)                                        ===>  #(0 1 4 9 16)
3607
3608Like in SRFI-1, this procedure allows the arguments to be of unequal
3609length; it terminates when the shortest list runs out.  This is a
3610CHICKEN extension to R7RS.
3611
3612<procedure>(string-for-each proc string[1] string[2] ...)</procedure>
3613
3614It is an error if proc does not accept as many arguments as there are strings.
3615The arguments to string-for-each are like the arguments to string-map, but
3616string-for-each calls
3617proc for its side effects rather than for its values. Unlike string-map,
3618string-for-each is guaranteed to call
3619proc on the elements of the
3620strings in order from the first element(s) to the last, and the value returned
3621by string-for-each is unspecified. If more than one
3622string is given and not all strings have the same length, string-for-each
3623terminates when the shortest string runs out. It is an error for
3624proc to mutate any of the strings.
3625
3626 (let ((v '()))
3627   (string-for-each
3628    (lambda (c) (set! v (cons (char->integer c) v)))
3629    "abcde")
3630   v)                          ==>  (101 100 99 98 97)
3631
3632<procedure>(vector-for-each proc vector[1] vector[2] ...)</procedure>
3633
3634It is an error if proc does not accept as many arguments as there are vectors.
3635The arguments to vector-for-each are like the arguments to vector-map, but
3636vector-for-each calls
3637proc for its side effects rather than for its values. Unlike vector-map,
3638vector-for-each is guaranteed to call
3639proc on the elements of the
3640vectors in order from the first element(s) to the last, and the value returned
3641by vector-for-each is unspecified. If more than one
3642vector is given and not all vectors have the same length, vector-for-each
3643terminates when the shortest vector runs out. It is an error for
3644proc to mutate any of the vectors.
3645
3646 (let ((v (make-list 5)))
3647   (vector-for-each
3648    (lambda (i) (list-set! v i (* i i)))
3649    '#(0 1 2 3 4))
3650   v)                                 ==>  (0 1 4 9 16)
3651
3652<procedure>(call-with-current-continuation proc)</procedure><br>
3653<procedure>(call/cc proc)</procedure><br>
3654
3655Proc must be a procedure of one argument. The procedure
3656call-with-current-continuation packages up the current continuation
3657(see the rationale below) as an "escape procedure" and passes it as
3658an argument to proc. The escape procedure is a Scheme procedure that,
3659if it is later called, will abandon whatever continuation is in effect
3660at that later time and will instead use the continuation that was in
3661effect when the escape procedure was created. Calling the escape
3662procedure may cause the invocation of before and after thunks installed
3663using dynamic-wind.
3664
3665The escape procedure accepts the same number of arguments as the
3666continuation to the original call to call-with-current-continuation.
3667Except for continuations created by the call-with-values procedure, all
3668continuations take exactly one value. The effect of passing no value or
3669more than one value to continuations that were not created by
3670call-with-values is unspecified.
3671
3672The escape procedure that is passed to proc has unlimited extent just
3673like any other procedure in Scheme. It may be stored in variables or
3674data structures and may be called as many times as desired.
3675
3676The following examples show only the most common ways in which
3677call-with-current-continuation is used. If all real uses were as simple
3678as these examples, there would be no need for a procedure with the
3679power of call-with-current-continuation.
3680
3681 (call-with-current-continuation
3682   (lambda (exit)
3683     (for-each (lambda (x)
3684                 (if (negative? x)
3685                     (exit x)))
3686               '(54 0 37 -3 245 19))
3687     #t))                                ===>  -3
3688 
3689 (define list-length
3690   (lambda (obj)
3691     (call-with-current-continuation
3692       (lambda (return)
3693         (letrec ((r
3694                   (lambda (obj)
3695                     (cond ((null? obj) 0)
3696                           ((pair? obj)
3697                            (+ (r (cdr obj)) 1))
3698                           (else (return #f))))))
3699           (r obj))))))
3700 
3701 (list-length '(1 2 3 4))                    ===>  4
3702 
3703 (list-length '(a b . c))                    ===>  #f
3704
3705Rationale:
3706
3707A common use of call-with-current-continuation is for structured,
3708non-local exits from loops or procedure bodies, but in fact
3709call-with-current-continuation is extremely useful for implementing
3710a wide variety of advanced control structures.
3711
3712Whenever a Scheme expression is evaluated there is a continuation
3713wanting the result of the expression. The continuation represents
3714an entire (default) future for the computation. If the expression
3715is evaluated at top level, for example, then the continuation might
3716take the result, print it on the screen, prompt for the next input,
3717evaluate it, and so on forever. Most of the time the continuation
3718includes actions specified by user code, as in a continuation that
3719will take the result, multiply it by the value stored in a local
3720variable, add seven, and give the answer to the top level
3721continuation to be printed. Normally these ubiquitous continuations
3722are hidden behind the scenes and programmers do not think much
3723about them. On rare occasions, however, a programmer may need to
3724deal with continuations explicitly. Call-with-current-continuation
3725allows Scheme programmers to do that by creating a procedure that
3726acts just like the current continuation.
3727
3728Most programming languages incorporate one or more special-purpose
3729escape constructs with names like exit, return, or even goto. In
37301965, however, Peter Landin [16] invented a general purpose escape
3731operator called the J-operator. John Reynolds [24] described a
3732simpler but equally powerful construct in 1972. The catch special
3733form described by Sussman and Steele in the 1975 report on Scheme
3734is exactly the same as Reynolds's construct, though its name came
3735from a less general construct in MacLisp. Several Scheme
3736implementors noticed that the full power of the catch construct
3737could be provided by a procedure instead of by a special syntactic
3738construct, and the name call-with-current-continuation was coined
3739in 1982. This name is descriptive, but opinions differ on the
3740merits of such a long name, and some people use the name call/cc
3741instead.
3742
3743<procedure>(values obj ...)</procedure><br>
3744
3745Delivers all of its arguments to its continuation. Except for
3746continuations created by the call-with-values procedure, all
3747continuations take exactly one value. Values might be defined as
3748follows:
3749
3750 (define (values . things)
3751   (call-with-current-continuation
3752     (lambda (cont) (apply cont things))))
3753
3754<procedure>(call-with-values producer consumer)</procedure><br>
3755
3756Calls its producer argument with no values and a continuation that,
3757when passed some values, calls the consumer procedure with those values
3758as arguments. The continuation for the call to consumer is the
3759continuation of the call to call-with-values.
3760
3761 (call-with-values (lambda () (values 4 5))
3762                   (lambda (a b) b))
3763                                                            ===>  5
3764 
3765 (call-with-values * -)                                     ===>  -1
3766
3767<procedure>(dynamic-wind before thunk after)</procedure><br>
3768
3769Calls thunk without arguments, returning the result(s) of this call.
3770Before and after are called, also without arguments, as required by the
3771following rules (note that in the absence of calls to continuations
3772captured using call-with-current-continuation the three arguments are
3773called once each, in order). Before is called whenever execution enters
3774the dynamic extent of the call to thunk and after is called whenever it
3775exits that dynamic extent. The dynamic extent of a procedure call is
3776the period between when the call is initiated and when it returns. In
3777Scheme, because of call-with-current-continuation, the dynamic extent
3778of a call may not be a single, connected time period. It is defined as
3779follows:
3780
3781*   The dynamic extent is entered when execution of the body of the
3782    called procedure begins.
3783
3784*   The dynamic extent is also entered when execution is not within the
3785    dynamic extent and a continuation is invoked that was captured
3786    (using call-with-current-continuation) during the dynamic extent.
3787
3788*   It is exited when the called procedure returns.
3789
3790*   It is also exited when execution is within the dynamic extent and a
3791    continuation is invoked that was captured while not within the
3792    dynamic extent.
3793
3794If a second call to dynamic-wind occurs within the dynamic extent of
3795the call to thunk and then a continuation is invoked in such a way that
3796the afters from these two invocations of dynamic-wind are both to be
3797called, then the after associated with the second (inner) call to
3798dynamic-wind is called first.
3799
3800If a second call to dynamic-wind occurs within the dynamic extent of
3801the call to thunk and then a continuation is invoked in such a way that
3802the befores from these two invocations of dynamic-wind are both to be
3803called, then the before associated with the first (outer) call to
3804dynamic-wind is called first.
3805
3806If invoking a continuation requires calling the before from one call to
3807dynamic-wind and the after from another, then the after is called
3808first.
3809
3810The effect of using a captured continuation to enter or exit the
3811dynamic extent of a call to before or after is undefined.  However,
3812in CHICKEN it is safe to do this, and they will execute in the outer
3813dynamic context of the {{dynamic-wind}} form.
3814
3815 (let ((path '())
3816       (c #f))
3817   (let ((add (lambda (s)
3818                (set! path (cons s path)))))
3819     (dynamic-wind
3820       (lambda () (add 'connect))
3821       (lambda ()
3822         (add (call-with-current-continuation
3823                (lambda (c0)
3824                  (set! c c0)
3825                  'talk1))))
3826       (lambda () (add 'disconnect)))
3827     (if (< (length path) 4)
3828         (c 'talk2)
3829         (reverse path))))
3830 
3831                 ===> (connect talk1 disconnect
3832                       connect talk2 disconnect)
3833
3834=== Exceptions
3835
3836This section describes Scheme's exception-handling and exception-raising
3837procedures.
3838
3839Exception handlers are one-argument procedures that determine the action the
3840program takes when an exceptional situation is signaled. The system implicitly
3841maintains a current exception handler in the dynamic environment.
3842
3843The program raises an exception by invoking the current exception handler,
3844passing it an object encapsulating information about the exception. Any
3845procedure accepting one argument can serve as an exception handler and any
3846object can be used to represent an exception.
3847
3848<procedure>(with-exception-handler handler thunk)</procedure>
3849
3850It is an error if handler does not accept one argument. It is also an error if
3851thunk does not accept zero arguments.
3852The with-exception-handler procedure returns the results of invoking
3853thunk.
3854Handler is installed as the current exception handler in the dynamic
3855environment used for the invocation of
3856thunk.
3857
3858 (call-with-current-continuation
3859  (lambda (k)
3860   (with-exception-handler
3861    (lambda (x)
3862     (display "condition: ")
3863     (write x)
3864     (newline)
3865     (k 'exception))
3866    (lambda ()
3867     (+ 1 (raise 'an-error))))))
3868          ==> exception and prints "condition: an-error"
3869
3870 (with-exception-handler
3871  (lambda (x)
3872   (display "something went wrong\n"))
3873  (lambda ()
3874   (+ 1 (raise 'an-error))))
3875
3876prints  "something went wrong"
3877After printing, the second example then raises another exception.
3878
3879<procedure>(raise obj)</procedure>
3880
3881Raises an exception by invoking the current exception handler on
3882obj. The handler is called with the same dynamic environment as that of the
3883call to raise, except that the current exception handler is the one that was in
3884place when the handler being called was installed. If the handler returns, a
3885secondary exception is raised in the same dynamic environment as the handler.
3886The relationship between
3887obj and the object raised by the secondary exception is unspecified.
3888
3889<procedure>(raise-continuable obj)</procedure>
3890
3891Raises an exception by invoking the current exception handler on
3892obj. The handler is called with the same dynamic environment as the call to
3893raise-continuable, except that: (1) the current exception handler is the one
3894that was in place when the handler being called was installed, and (2) if the
3895handler being called returns, then it will again become the current exception
3896handler. If the handler returns, the values it returns become the values
3897returned by the call to raise-continuable.
3898
3899 (with-exception-handler
3900   (lambda (con)
3901     (cond
3902       ((string? con)
3903        (display con))
3904       (else
3905        (display "a warning has been issued")))
3906     42)
3907   (lambda ()
3908     (+ (raise-continuable "should be a number")
3909        23)))
3910     prints: "should be a number"
3911     ==> 65
3912
3913<procedure>(error [location] message obj ...)</procedure>
3914
3915Message should be a string.
3916Raises an exception as if by calling raise on a newly allocated
3917implementation-defined object which encapsulates the information provided by
3918message, as well as any
3919objs, known as the irritants. The procedure error-object? must return #t on
3920such objects.
3921
3922 (define (null-list? l)
3923   (cond ((pair? l) #f)
3924         ((null? l) #t)
3925         (else
3926           (error
3927             "null-list?: argument out of domain"
3928             l))))
3929
3930If location is given and a symbol, it indicates the name of the procedure where
3931the error occurred.
3932
3933<procedure>(error-object? obj)</procedure>
3934
3935Returns #t if
3936obj is an object created by error or one of an implementation-defined set of
3937objects. Otherwise, it returns #f. The objects used to signal errors, including
3938those which satisfy the predicates file-error? and read-error?, may or may not
3939satisfy error-object?.
3940
3941<procedure>(error-object-message error-object)</procedure>
3942
3943Returns the message encapsulated by
3944error-object.
3945
3946<procedure>(error-object-irritants error-object)</procedure>
3947
3948Returns a list of the irritants encapsulated by
3949error-object.
3950
3951<procedure>(read-error? obj)</procedure><br>
3952<procedure>(file-error? obj)</procedure>
3953
3954Error type predicates. Returns #t if
3955obj is an object raised by the read procedure or by the inability to open an
3956input or output port on a file, respectively. Otherwise, it returns #f.
3957
3958=== Eval
3959
3960<procedure>(eval expression [environment-specifier])</procedure><br>
3961
3962Evaluates expression in the specified environment and returns its
3963value. Expression must be a valid Scheme expression represented as
3964data, and environment-specifier must be a value returned by one of the
3965three procedures described below. Implementations may extend eval to
3966allow non-expression programs (definitions) as the first argument and
3967to allow other values as environments, with the restriction that eval
3968is not allowed to create new bindings in the environments associated
3969with null-environment or scheme-report-environment.
3970
3971 (eval '(* 7 3) (scheme-report-environment 5))
3972                                                            ===>  21
3973 
3974 (let ((f (eval '(lambda (f x) (f x x))
3975                (null-environment 5))))
3976   (f + 10))
3977                                                            ===>  20
3978
3979The {{environment-specifier}} is optional, and if not provided it
3980defaults to the value of {{(interaction-environment)}}.  This is a
3981CHICKEN extension to R7RS, which, though strictly nonportable, is very
3982common among Scheme implementations.
3983
3984=== Input and output
3985
3986==== Ports
3987
3988Ports represent input and output devices. To Scheme, an input port is a Scheme
3989object that can deliver data upon command, while an output port is a Scheme
3990object that can accept data.
3991
3992Different port types operate on different data. Scheme implementations are
3993required to support textual ports and binary ports, but may also provide other
3994port types.
3995
3996A textual port supports reading or writing of individual characters from or to
3997a backing store containing characters using read-char and write-char below, and
3998it supports operations defined in terms of characters, such as read and write.
3999
4000A binary port supports reading or writing of individual bytes from or to a
4001backing store containing bytes using read-u8 and write-u8 below, as well as
4002operations defined in terms of bytes. Whether the textual and binary port types
4003are disjoint is implementation-dependent.
4004
4005Ports can be used to access files, devices, and similar things on the host
4006system on which the Scheme program is running.
4007
4008<procedure>(call-with-port port proc)</procedure>
4009
4010It is an error if
4011proc does not accept one argument.
4012The call-with-port procedure calls
4013proc with
4014port as an argument. If
4015proc returns, then the port is closed automatically and the values yielded by
4016the
4017proc are returned. If
4018
4019proc does not return, then the port must not be closed automatically unless it
4020is possible to prove that the port will never again be used for a read or write
4021operation.
4022
4023    Rationale: Because Scheme's escape procedures have unlimited extent, it is
4024    possible to escape from the current continuation but later to resume it. If
4025    implementations were permitted to close the port on any escape from the
4026    current continuation, then it would be impossible to write portable code
4027    using both call-with-current-continuation and call-with-port.
4028
4029Ports represent input and output devices. To Scheme, an input port is a
4030Scheme object that can deliver characters upon command, while an output
4031port is a Scheme object that can accept characters.
4032
4033<procedure>(input-port? obj)</procedure><br>
4034<procedure>(output-port? obj)</procedure><br>
4035<procedure>(textual-port? obj)</procedure><br>
4036<procedure>(binary-port? obj)</procedure><br>
4037<procedure>(port? obj)</procedure>
4038
4039These procedures return #t if
4040obj is an input port, output port, textual port, binary port, or any kind of
4041port, respectively. Otherwise they return #f.
4042
4043<procedure>(input-port-open? port)</procedure><br>
4044<procedure>(output-port-open? port)</procedure>
4045
4046Returns #t if
4047port is still open and capable of performing input or output, respectively, and
4048#f otherwise.
4049
4050<procedure>(current-input-port [port])</procedure><br>
4051<procedure>(current-output-port [port])</procedure><br>
4052<procedure>(current-error-port [port])</procedure><br>
4053
4054Returns the current default input, output or error port.
4055
4056If the optional {{port}} argument is passed, the current input or
4057output port is changed to the provided port.  It can also be used with
4058{{parameterize}} to temporarily bind the port to another value.  This
4059is a CHICKEN extension to the R7RS standard.
4060
4061Note that the default output port is not buffered. Use
4062[[Module (chicken port)#set-buffering-mode!|{{set-buffering-mode!}}]]
4063if you need a different behavior.
4064
4065<procedure>(open-input-file filename [mode ...])</procedure><br>
4066<procedure>(open-binary-input-file filename [mode ...])</procedure>
4067
4068Takes a string naming an existing file and returns an input port
4069capable of delivering textual or binary data from the file. If the file cannot be
4070opened, an error is signalled.
4071
4072Additional {{mode}} arguments can be passed in, which should be any of
4073the keywords {{#:text}} or {{#:binary}}.  These indicate the mode in
4074which to open the file (this has an effect on non-UNIX platforms
4075only).  The extra {{mode}} arguments are CHICKEN extensions to the
4076R7RS standard.
4077
4078<procedure>(close-port port)</procedure><br>
4079<procedure>(close-input-port port)</procedure><br>
4080<procedure>(close-output-port port)</procedure><br>
4081
4082Closes the resource associated with
4083port, rendering the
4084port incapable of delivering or accepting data. It is an error to apply the
4085last two procedures to a port which is not an input or output port,
4086respectively. Scheme implementations may provide ports which are simultaneously
4087input and output ports, such as sockets; the close-input-port and
4088close-output-port procedures can then be used to close the input and output
4089sides of the port independently.
4090
4091These routines have no effect if the port has already been closed.
4092
4093<procedure>(open-input-string string)</procedure>
4094
4095Takes a string and returns a textual input port that delivers characters from
4096the string. If the string is modified, the effect is unspecified.
4097
4098<procedure>(open-output-string)</procedure>
4099
4100Returns a textual output port that will accumulate characters for retrieval by
4101get-output-string.
4102
4103<procedure>(get-output-string port)</procedure>
4104
4105It is an error if
4106port was not created with open-output-string.
4107Returns a string consisting of the characters that have been output to the port
4108so far in the order they were output. If the result string is modified, the
4109effect is unspecified.
4110
4111 (parameterize
4112     ((current-output-port
4113       (open-output-string)))
4114     (display "piece")
4115     (display " by piece ")
4116     (display "by piece.")
4117     (newline)
4118     (get-output-string (current-output-port)))
4119   ==> "piece by piece by piece.\n"
4120
4121<procedure>(open-input-bytevector bytevector)</procedure>
4122
4123Takes a bytevector and returns a binary input port that delivers bytes from the
4124bytevector.
4125
4126<procedure>(open-output-bytevector)</procedure>
4127
4128Returns a binary output port that will accumulate bytes for retrieval by
4129get-output-bytevector.
4130
4131<procedure>(get-output-bytevector port)</procedure>
4132
4133It is an error if
4134port was not created with open-output-bytevector.
4135Returns a bytevector consisting of the bytes that have been output to the port
4136so far in the order they were output.
4137
4138==== Input
4139
4140If port is omitted from any input procedure, it defaults to the value returned by
4141(current-input-port). It is an error to attempt an input operation on a closed
4142port.
4143
4144<procedure>(read-char [port])</procedure><br>
4145
4146Returns the next character available from the input port, updating the
4147port to point to the following character. If no more characters are
4148available, an end of file object is returned. Port may be omitted, in
4149which case it defaults to the value returned by current-input-port.
4150
4151<procedure>(peek-char [port])</procedure><br>
4152
4153Returns the next character available from the input port, without
4154updating the port to point to the following character. If no more
4155characters are available, an end of file object is returned. Port may
4156be omitted, in which case it defaults to the value returned by
4157current-input-port.
4158
4159Note:   The value returned by a call to peek-char is the same as
4160the value that would have been returned by a call to read-char with
4161the same port. The only difference is that the very next call to
4162read-char or peek-char on that port will return the value returned
4163by the preceding call to peek-char. In particular, a call to
4164peek-char on an interactive port will hang waiting for input
4165whenever a call to read-char would have hung.
4166
4167<procedure>(read-line [port])</procedure>
4168
4169Returns the next line of text available from the textual input
4170port, updating the
4171port to point to the following character. If an end of line is read, a string
4172containing all of the text up to (but not including) the end of line is
4173returned, and the port is updated to point just past the end of line. If an end
4174of file is encountered before any end of line is read, but some characters have
4175been read, a string containing those characters is returned. If an end of file
4176is encountered before any characters are read, an end-of-file object is
4177returned. For the purpose of this procedure, an end of line consists of either
4178a linefeed character, a carriage return character, or a sequence of a carriage
4179return character followed by a linefeed character. Implementations may also
4180recognize other end of line characters or sequences.
4181
4182<procedure>(eof-object? obj)</procedure><br>
4183
4184Returns #t if obj is an end of file object, otherwise returns #f. The
4185precise set of end of file objects will vary among implementations, but
4186in any case no end of file object will ever be an object that can be
4187read in using read.
4188
4189<procedure>(eof-object)</procedure>
4190
4191Returns an end-of-file object, not necessarily unique.
4192
4193<procedure>(char-ready? [port])</procedure><br>
4194
4195Returns #t if a character is ready on the input port and returns #f
4196otherwise. If char-ready returns #t then the next read-char operation
4197on the given port is guaranteed not to hang. If the port is at end of
4198file then char-ready? returns #t. Port may be omitted, in which case it
4199defaults to the value returned by current-input-port.
4200
4201Rationale:   Char-ready? exists to make it possible for a program
4202to accept characters from interactive ports without getting stuck
4203waiting for input. Any input editors associated with such ports
4204must ensure that characters whose existence has been asserted by
4205char-ready? cannot be rubbed out. If char-ready? were to return #f
4206at end of file, a port at end of file would be indistinguishable
4207from an interactive port that has no ready characters.
4208
4209<procedure>(read-string k [port])</procedure>
4210
4211See [[Module (chicken io)|(chicken io) module]] for more information.
4212
4213<procedure>(read-u8 [port])</procedure>
4214
4215Returns the next byte available from the binary input
4216port, updating the
4217port to point to the following byte. If no more bytes are available, an
4218end-of-file object is returned.
4219
4220<procedure>(peek-u8 [port])</procedure>
4221
4222Returns the next byte available from the binary input
4223port, but without updating the
4224port to point to the following byte. If no more bytes are available, an
4225end-of-file object is returned.
4226
4227<procedure>(u8-ready? [port])</procedure>
4228
4229Returns #t if a byte is ready on the binary input
4230port and returns #f otherwise. If u8-ready? returns #t then the next read-u8
4231operation on the given
4232port is guaranteed not to hang. If the
4233port is at end of file then u8-ready?​ ​returns #t.
4234
4235<procedure>(read-bytevector k [port])</procedure><br>
4236<procedure>(read-bytevector! bytevector [port [start [end]]])</procedure>
4237
4238See [[Module (chicken io)|(chicken io) module]] for more information.
4239
4240==== Output
4241
4242If port is omitted from any output procedure, it defaults to the value returned by
4243(current-output-port). It is an error to attempt an output operation on a
4244closed port.
4245
4246<procedure>(newline)</procedure><br>
4247<procedure>(newline port)</procedure><br>
4248
4249Writes an end of line to port. Exactly how this is done differs from
4250one operating system to another. Returns an unspecified value. The port
4251argument may be omitted, in which case it defaults to the value
4252returned by current-output-port.
4253
4254<procedure>(write-char char)</procedure><br>
4255<procedure>(write-char char port)</procedure><br>
4256
4257Writes the character char (not an external representation of the
4258character) to the given port and returns an unspecified value. The port
4259argument may be omitted, in which case it defaults to the value
4260returned by current-output-port.
4261
4262<procedure>(write-string string [port [start [end]]])</procedurew>
4263
4264Writes the characters of
4265string from
4266start to
4267end in left-to-right order to the textual output
4268port.
4269
4270<procedure>(write-u8 byte [port])</procedure>
4271
4272Writes the
4273byte to the given binary output
4274port and returns an unspecified value.
4275
4276<procedure>(write-bytevector bytevector [port [start [end]]])</procedure>
4277
4278See [[Module (chicken bytevector)|The (chicken bytevector) module]] for more
4279information.
4280
4281<procedure>(flush-output-port [port])</procedure>
4282
4283Flushes any buffered output from the buffer of output-port to the underlying
4284file or device and returns an unspecified value.
4285
4286==== System interface
4287
4288Questions of system interface generally fall outside of the domain of
4289this report. However, the following operations are important enough to
4290deserve description here.
4291
4292<procedure>(features)</procedure>
4293
4294Returns a list of the feature identifiers which cond-expand treats as true. It
4295is an error to modify this list. Here is an example of what features might
4296return:
4297
4298 (features)  ==>
4299   (r7rs ratios exact-complex full-unicode
4300    gnu-linux little-endian
4301    fantastic-scheme
4302    fantastic-scheme-1.0
4303    space-ship-control-system)
4304
4305---
4306Previous: [[Module scheme]]
4307
4308Next: [[Module (scheme case-lambda)]]
Trap